Home > database >  How to merge data from two different JSON file
How to merge data from two different JSON file

Time:06-29

I have a json file while have multiple data of some products. For example:

[
 {
  "id": 11,
  "name": "Car"
 }
]

On the other hand, I have another json file. Which have some data matching with the id of the previous json file. For example:

[
 {
  "id": 11,
  "price": 50
 }
]

How can I parse these two json file data and map them and show on my UI.

CodePudding user response:

Create new array which combines propety of the both objects like this:

const json1 = JSON.parse('[{"id": 11,"name": "Car"}]');
const json2 = JSON.parse('[{"id": 11,"price": 50}]');

const mappedObject = [];

await json1.forEach(async item => {
    const {id, name} = item;
    const priceObject = await json2.filter(x => x.id === id);
    const {price } = priceObject;
    console.log(priceObject);
    mappedObject.push({
      id,
      name,
      price
    });
});

console.log(mappedObject);

CodePudding user response:

var a = [
 {
  "id": 11,
  "name": "Car"
 }
]
var b = [
 {
  "id": 11,
  "price": 50
 }
]

var result = a.reduce((accumulator, item) => {
  var exist = accumulator.find(v => v.id === item.id)
  if (exist) {
    exist = Object.assign(exist, item)
  }
  return accumulator
}, b)

console.log(result)

  • Related