-1

I'm trying to compare two objects with the purpose of logging out the ones which do not exist in the first object.

First Object

this.Object1 =[{id:1, name,'Coke'}, {id:2, name,Fanta},{id:3, name,'Sprite'}, {id:4, name,'Pepsi'}]

Second Object

this.Object 2 = [{id:1, name,'Coke'}, {id:2, name,'Fanta'},{id:5, name,'Miranda'}, {id:6, name,'Alvaro', id:7, 'Orange Juice'}]

What I want to achieve is to loop through object1 and find their ids that don't exist in object2 and push those in there

so the final result of object1 will be like this

[{id:1, name,'Coke'}, {id:2, name,Fanta},{id:3, name,'Sprite'}, {id:4, name,'Pepsi',id:5, name,'Miranda'}, {id:6, name,'Alvaro', id:7, 'Orange Juice'}]

Script

for (let r = 0; r < this.object1.length; r++) {
  for (let i = 0; i < this.object2.length; i++) {
      if (this.object1.id != this.object2[i].id) {
      this.object2.push(this.object1[r]);
      console.log(this.object1[i].name  + ' does not exist');
      }
  }
}
neiza
  • 265
  • 4
  • 15

3 Answers3

2

Can you try this? it may help you

obj1 = [{id:1, name:'Coke'}, {id:2, name: 'Fanta'},{id:3, name: 'Sprite'}, {id:4, name:'Pepsi'}]
obj2 = [{id:1, name:'Coke'}, {id:2, name:'Fanta'},{id:5, name:'Miranda'}, {id:6, name:'Alvaro'},{ id:7, name: 'Orange Juice'}]
ids = []
obj1.map(res => {ids.push(res.id)})
obj2.map(res => {
    if(!ids.includes(res.id)){
        obj1.push(res)
    }
})
// [ { id: 1, name: 'Coke' }, { id: 2, name: 'Fanta' }, { id: 3, name: 'Sprite' }, { id: 4, name: 'Pepsi' }, { id: 5, name: 'Miranda' }, { id: 6, name: 'Alvaro' }, { id: 7, name: 'Orange Juice' } ]
0

Could you try this

var o = [{id:1, name:'Coke'}, {id:2, name:'Fanta'},{id:3, name:'Sprite'}, {id:4, name:'Pepsi'}];
var oo= [{id:1, name:'Coke'}, {id:5, name:'ZZZ'}, {id:6, name:'YYY'}, {id:9, name:'XXX'}, {id:4, name:'Pepsi'}];

var unique = oo.filter(x=>o.findIndex(y=>y.id===x.id)===-1);

console.log(unique);
var all = o.concat(unique);
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
kunal verma
  • 456
  • 5
  • 13
0

You have some issues/tyops in your objects. {id:3, name,'Sprite'}needs to be {id:3, name: 'Sprite'} for example. When this is fixed you can write something like this if using es6:

const arr1 = [
  {id:1, name:'Coke'},
  {id:2, name: 'Fanta'},
  {id:3, name: 'Sprite'},
  {id:4, name: 'Pepsi'}
]

const arr2 = [
  {id:1, name: 'Coke'}, 
  {id:2, name: 'Fanta'},
  {id:5, name: 'Miranda'}, 
  {id:6, name: 'Alvaro'},
  {id:7, name: 'Orange Juice'},
]

const getIds = (arr) => arr.map(i => i.id)

const diff = getIds(arr2).filter((item) => getIds(arr1).includes(item))

console.log('Diff:', diff)
Jonas Johansson
  • 417
  • 3
  • 8