简体   繁体   中英

How to check if array contains objects

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.

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 ) 
}

(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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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