在Javascript中我有一个对象数组:
var errors = [
{ code: 35, name: "Authentication" },
{ code: 34, name: "Validation" }
]
可重用函数的最佳选项是什么,检查此类型的数组是否包含代码为== XYZ的项目?如果有,则返回包含所有这些项的数组。
答案 0 :(得分:4)
var errors = [
{ code: 35, name: "Authentication" },
{ code: 34, name: "Validation" }
]
var result = errors.filter(itm => itm.code == "xyz");
上面的代码会在新数组code
"xyz"
的属性result
的对象
答案 1 :(得分:1)
使用filter
:
var errors = [
{ code: 35, name: "Authentication" },
{ code: 34, name: "Validation" }
]
var find = function(code) {
return errors.filter(function(i) { return i.code === code })
}
find(34) // [{ code: 34, name: "Validation" }]
请参阅this fiddle
答案 2 :(得分:0)
您可以尝试这样的事情:
Array.prototype.findByValueOfObject = function(key, value) {
return this.filter(function(item) {
return (item[key] === value);
});
}
var errors = [
{ code: 35, name: "Authentication" },
{ code: 34, name: "Validation" }
];
print(errors.findByValueOfObject("code", "xyz"));
print(errors.findByValueOfObject("code", 35));
print(errors.findByValueOfObject("name", "Validation"));
function print(obj){
document.write("<pre>" + JSON.stringify(obj,0,4) + "</pre><br/> ----------");
}
&#13;