Dcook
Dcook

Reputation: 961

Compare two json object and fetch data from one into another based on matching key

I have two json response something like this, basically need to pull the 'status' from res2 and insert into res1 based on matching uid

res1 = [
  {
    uid: 'RBZ7K2122715',
    Model: Mod1,
    lastReceived: date1
  },
  {
    uid: 'RBZ7K2123333',
    Model: Mod2,
    lastReceived: date2
  }
]

res2 = [
  {
    uid: 'RBZ7K2122715',
    Status: [ [Object1], [Object2], [Object3] ]
  },
  {
    vin: 'RBZ7K2123333',
    Status: [ [Object4], [Object5] ]
  }
]

I'd like to get response something like this:

result = [
      {
        uid: 'RBZ7K2122715',
        Model: Mod1,
        lastReceived: date1,
        Status: [ [Object1], [Object2], [Object3] ]
      },
      {
        uid: 'RBZ7K2123333',
        Model: Mod2,
        lastReceived: date2,
        Status: [[Object4], [Object5]]
      }
    ]

In case any particular uid is not present in res1 but present in res2 in that case populate res1 fileds with 'N/A' and vice-versa

Upvotes: 0

Views: 115

Answers (2)

wangdev87
wangdev87

Reputation: 8751

Loop res1 using map, find the res2's item that has the same uid and return the new object.

const result = res1.map(item => {
  const index = res2.findIndex(item2 => item2.uid === item.uid)
  return {
    ...item,
    Status: index !== -1 ? res2[index].Status : []
  }
});

Upvotes: 1

Derek Wang
Derek Wang

Reputation: 10194

Using Array.prototype.reduce, you can group by uid and merge the items.

const res1 = [
  {
    uid: 'RBZ7K2122715',
    Model: 'Mod1',
    lastReceived: 'date1'
  },
  {
    uid: 'RBZ7K2123333',
    Model: 'Mod2',
    lastReceived: 'date2'
  }
];

const res2 = [
  {
    uid: 'RBZ7K2122715',
    Status: [ ['Object1'], ['Object2'], ['Object3'] ]
  },
  {
    vin: 'RBZ7K2123333',
    Status: [ ['Object4'], ['Object5'] ]
  }
];

const groupBy = [...res1, ...res2].reduce((acc, cur) => {
  acc[cur.uid] ? acc[cur.uid] = {
    ...acc[cur.uid], ...cur
  } : acc[cur.uid] = cur;
  return acc;
}, {});

const output = Object.values(groupBy);
console.log(output);

Upvotes: 2

Related Questions