-1

I have an array of objects as follows

[{name: "jack", age: 10}, {name: "john", age: 15}]

Consider that i have an object

{name: "jack", age: 10}

Now i need to check if this object exist in the array. If all the properties(name, age) of the object matches, then display an alert on the page.

How to accomplish this using pure javascript?

prajeesh
  • 2,202
  • 6
  • 34
  • 59
  • 2
    accomplish it by checking all the "primitive" properties match - Object.keys/Object.values or Object.entries can help – Jaromanda X May 25 '18 at 06:58
  • The same object literal never exists anywhere else ... – Teemu May 25 '18 at 06:59
  • possible duplicate of https://stackoverflow.com/questions/4587061/how-to-determine-if-object-is-in-array – DaCh May 25 '18 at 07:00
  • Possible duplicate of [How to determine if object is in array](https://stackoverflow.com/questions/4587061/how-to-determine-if-object-is-in-array) – DaCh May 25 '18 at 07:00

4 Answers4

0

Use Array.some, Array.every and Object.entries

A match will be counted if

  • There are equal number of keys
  • There is a match for every key/value pair

var arr = [{name: "jack", age: 10}, {name: "john", age: 15}];

var input = {name: "jack", age: 10};

var result = arr.some((o) => Object.entries(input).every(([k,v]) => o[k] === v) && Object.keys(input).length === Object.keys(o).length);

console.log(result);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

Try this:

var data = [{name: "jack", age: 10}, {name: "john", age: 15}];
var input = {name: "jack", age: 10};
for(var i=0;i<data.length;i++)
{
    if(data[i].name==input.name && data[i].age == input.age)
    {
        alert('matched');
        break;
    }
}
Harsh Jaswal
  • 447
  • 3
  • 14
0

This may be a bad performing method, but it would cover nested object cases with ease. Also this is only suited if ALL key/value pairs must match and that the key/value pairs were defined in the same order.

let c = [{name: "jack", age: 10}, {name: "john", age: 15}],
    s = {name: "jack", age: 10};

console.log(c.filter(e => JSON.stringify(s) === JSON.stringify(e)));
wiesion
  • 2,349
  • 12
  • 21
0

You can try this if you don't want to check for index of object inside array object

var obj = [{name: "jack", age: 10}, {name: "john", age: 15}];

var checkObj = {name: "john", age: 15};

if(JSON.stringify(obj).indexOf(JSON.stringify(checkObj)) >= 0){
  console.log("Object Available");
}else{
  console.log("Object Not Available");
}
Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40