I am performing push operation to an array of objects. My code looks similar as shown below,
var obj = {"id":1, "fname":"john", "lname":"doe"};
var userArray = [{
"id": 1,
"fname": "john",
"lname": "doe"
}, {
"id": 2,
"fname": "john",
"lname": "doe"
}];
userArray.forEach(function (element) {
if(element.id !== obj.id) {
userArray.push(obj);
}
});
console.log(userArray);
when i do push operation on userArray which already contains an object which i am pushing (from code it is var obj = {"id":1, "fname":"john", "lname":"doe"};) it pushes it to array on second pass in for loop.
Expected output should be userArray = [{"id": 1,"fname": "john","lname": "doe"}, {"id": 2, "fname": "john","lname": "doe"}];
but i am getting userArray = [{"id": 1,"fname": "john","lname": "doe"}, {"id": 2, "fname": "john","lname": "doe"}, {"id": 1,"fname": "john","lname": "doe"}];
How do i push only unique objects to array?
idif it fails for all the items in the array, then only add that object otherwise ignore it.false, inside the for loop, compare theid, if it matches set your flag value totrueand break out of loop. Outside the loop, check the value of flag, and add object only ifflagvalue isfalse.