1

I have array, created from json:

var array = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name2","group":"group2","id":"456", ...},
{"name":"name3","group":"group1","id":"789", ...}];

After I get another array:

var array1 = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name4","group":"group1","id":"987", ...}]

I need to push items from second array into first, but how can I check if first array contains objects from second array?

Each object in array contain more property and some of them are created dynamically so I can't check for example by indexOf(). All solutions that I found works only with simple objects like Int. It will be great if I could check by property "id" for example.

Ryan Schaefer
  • 3,047
  • 1
  • 26
  • 46
  • 4
    Possible duplicate of [How do I check if an array includes an object in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) – Yogesh Mar 06 '18 at 15:07

2 Answers2

2

Use find first

var newObj = {"name":"name2","group":"group2","id":"456"};
var value = array.find( s => s.id == newObj.id );  

Now push if the value is not found

if ( !value )
{
   array.push( newObj ) 
}
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

(More generic)you can do this one line using following (which will add all object which is not in array).

array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));

var array = [{"name":"name1","group":"group1","id":"123"},
             {"name":"name2","group":"group2","id":"456" },
             {"name":"name3","group":"group1","id":"789"}];

var array1 = [{"name":"name1","group":"group1","id":"123"},
              {"name":"name4","group":"group1","id":"987"}];

array=array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
console.log(array);
yajiv
  • 2,901
  • 2
  • 15
  • 25