admin管理员组文章数量:1405154
Exist an array with a lot of objects. Required to find an object or objects in this array by property.
Input obj:
var Obj = [
{"start": 0, "length": 3, "style": "text"},
{"start": 4, "length": 2, "style": "operator"},
{"start": 4, "length": 3, "style": "error"}
];
Output result: (search for "start" with value 4)
var result = [
{"start": 4, "length": 2, "style": "operator"},
{"start": 4, "length": 3, "style": "error"}
];
Exist an array with a lot of objects. Required to find an object or objects in this array by property.
Input obj:
var Obj = [
{"start": 0, "length": 3, "style": "text"},
{"start": 4, "length": 2, "style": "operator"},
{"start": 4, "length": 3, "style": "error"}
];
Output result: (search for "start" with value 4)
var result = [
{"start": 4, "length": 2, "style": "operator"},
{"start": 4, "length": 3, "style": "error"}
];
Share
Improve this question
asked Nov 25, 2013 at 14:47
NiLLNiLL
13.9k15 gold badges48 silver badges59 bronze badges
6
- Less than a minute to resolve your own problem! Amazing. – user1636522 Commented Nov 25, 2013 at 14:56
- (Stop drinking wared, you see double...) – user1636522 Commented Nov 25, 2013 at 14:59
- @wared What's wrong? This is just small tip in Q&A style. – NiLL Commented Nov 25, 2013 at 15:17
- Problem is that it's a mon and fairly trivial problem. Did you verify that there are no duplicates? – Blue Skies Commented Nov 25, 2013 at 15:49
- @BlueSkies I've found dups, but there top solutions are terrible. – NiLL Commented Nov 26, 2013 at 9:16
3 Answers
Reset to default 4Use filter function of array
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);
});
}
Compatible with all except IE6, IE7, IE8, but exist 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;
};
}
We can create an util function like below which works for filtering the array based on any key using the filter method of Array.
function filterObjects(objArr,key,value){
return objArr.filter(obj => obj[key]===value);
}
filterObjects(objArr,'name','Email');
本文标签: How to find object in array by property in javascriptStack Overflow
版权声明:本文标题:How to find object in array by property in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744887216a2630558.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论