简体   繁体   English

过滤对象数组中的项目

[英]Filter items in array of objects

In Javascript I have an array of objects: 在Javascript中,我有一个对象数组:

var errors = [
  { code: 35, name: "Authentication" },
  { code: 34, name: "Validation" }
]

What is the best option for a reusable function that checks if and array of this type has an item with code == XYZ? 对于可重用函数,最好的选择是什么,该函数检查此类型的数组是否具有代码== XYZ的项? If it has then return an array with all those items. 如果已经返回,则返回一个包含所有这些项的数组。

You can do it with Array.prototype.filter() 您可以使用Array.prototype.filter()

var errors = [
  { code: 35, name: "Authentication" },
  { code: 34, name: "Validation" }
]

var result = errors.filter(itm => itm.code == "xyz");

The above code will filter out the objects which has a property code with value "xyz" in a new array result 上面的代码将在新数组result过滤出具有属性code "xyz"的对象

Use filter : 使用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" }]

See this fiddle 看到这个小提琴

You can try something like this: 您可以尝试如下操作:

 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/> ----------"); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM