Filter Items In Array Of Objects
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 functi
Solution 1:
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
Solution 2:
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
Solution 3:
You can try something like this:
Array.prototype.findByValueOfObject = function(key, value) {
returnthis.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"));
functionprint(obj){
document.write("<pre>" + JSON.stringify(obj,0,4) + "</pre><br/> ----------");
}
Post a Comment for "Filter Items In Array Of Objects"