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,1001 gold badge29 silver badges48 bronze badges
asked Mar 6, 2018 at 15:06
1

2 Answers 2

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 ) 
}
answered Mar 6, 2018 at 15:09
Sign up to request clarification or add additional context in comments.

3 Comments

Or use array.some.
Yes, if only a boolean is required. However, find can be useful if existing value has to be updated.
@gurvinder372 That works, thank you. I expected that solution must be easy, but not expected that so easy :)
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);

answered Mar 6, 2018 at 15:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.