0

In Javascript I have an array of objects:

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? If it has then return an array with all those items.

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • Have you considered asking a search engine for "Filter items in array of objects"?? Or, well, stackoverflow?! – fast Mar 29 '16 at 12:25

3 Answers3

4

You can do it with 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

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
1

Use 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

cl3m
  • 2,791
  • 19
  • 21
0

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/> ----------");
}
Rajesh
  • 24,354
  • 5
  • 48
  • 79