如何在javascript中按属性查找数组中的对象
How to find object in array by property in javascript?
存在一个包含大量对象的数组。需要按属性查找此数组中的一个或多个对象。
输入对象:
var Obj = [
{"start": 0, "length": 3, "style": "text"},
{"start": 4, "length": 2, "style": "operator"},
{"start": 4, "length": 3, "style": "error"}
];
输出结果:(搜索值为4的"开始")
var result = [
{"start": 4, "length": 2, "style": "operator"},
{"start": 4, "length": 3, "style": "error"}
];
使用阵列的过滤功能
var Obj = [
{"start": 0, "length": 3, "style": "text"},
{"start": 4, "length": 2, "style": "operator"},
{"start": 4, "length": 3, "style": "error"}
];
var result = Obj.filter(x => x.start === 4);
console.log(result);
_findItemByValue(Obj,"start",4);
var _findItemByValue = function(obj, prop, value) {
return obj.filter(function(item) {
return (item[prop] === value);
});
}
兼容除IE6、IE7、IE8以外的所有产品,但存在polyfill。
if (!Array.prototype.filter) {
Array.prototype.filter = function (fn, context) {
var i,
value,
result = [],
length;
if (!this || typeof fn !== 'function' || (fn instanceof RegExp)) {
throw new TypeError();
}
length = this.length;
for (i = 0; i < length; i++) {
if (this.hasOwnProperty(i)) {
value = this[i];
if (fn.call(context, value, i, this)) {
result.push(value);
}
}
}
return result;
};
}
我们可以创建一个如下的util函数,该函数使用array的filter方法根据任何键过滤数组。
function filterObjects(objArr,key,value){
return objArr.filter(obj => obj[key]===value);
}
filterObjects(objArr,'name','Email');
相关文章:
- Lodash 从值数组中查找数组中的值
- 使用JS查找数组的平均值
- 查找数组javascript中包含的元素类型
- Undercore:查找数组中出现频率最高的对象
- 查找数组's按属性不存在于另一个数组中的对象
- 查找数组中项目包含子字符串的索引
- 按键查找数组中对象的索引
- 按链中的键查找数组元素
- 使用JavaScript查找数组中最近的日期
- 在Javascript中查找数组长度
- 正在查找数组中第一个匹配元素的索引
- Rhino 1.5 R5在查找数组差异时未正确评估JavaScript
- 查找数组值
- 如何在javascript中按属性查找数组中的对象
- 如何使用JavaScript查找数组中的最早日期
- 查找数组中最长的单词/字符串
- 如何查找数组中所有出现的元素的索引(Ramda.js方式)
- 查找数组中的下一个最高数字 - jquery
- 如何查找数组中另一个对象旁边的对象
- 按键查找数组中最接近的 2 个元素