Jon Jon - 11 months ago 111
Javascript Question

Merging The same specific json object in two different json arrays

I would like to merge the same specific json object on two different json arrays dependent on an json data ID.

JSON Data Set 1

{
"Product":[
{
"product_id": "123",
"location_id": "222",
"product_code": "abc",
},
{
"product_id": "456",
"location_id": "111",
"product_code": "xyz",
}
]
}


JSON Data set 2

{
"Location":[

{
"location_id": 111,
"location_name": "alpha"
},
{
"location_id": 222,
"location_name": "tango"
}


]
}


The Results would be something like this

{
"Product":[

{
"product_id": "456",
"location_id": "111",
"product_code": "xyz",
"location_name": "alpha"
},
{
"product_id": "123",
"location_id": "222",
"product_code": "abc",
"location_name": "tango"
}
]
}


So far this is the code I've done.

var finalJson = {};

_.each(_.keys(productArray,locationArray), function(key) {
finalJson[key] = _.flatten(_.zip(productArray[key], locationArray[key]));
});

console.log(finalJson);

Answer Source

A simple algorithm could be using nested loops to go through both arrays, like this:

let allProducts = [{
    "product_id": "123",
    "location_id": "222",
    "product_code": "abc",
  },
  {
    "product_id": "456",
    "location_id": "111",
    "product_code": "xyz",
  }
];


let allLocations = [

  {
    "location_id": 111,
    "location_name": "alpha"
  },
  {
    "location_id": 222,
    "location_name": "tango"
  }
];

let result = allProducts.map((product) => {
  let matchingLocation = allLocations.find((location) => {
    return location.location_id == product.location_id;
  });
  return Object.assign(product, matchingLocation);
})

console.log(result);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download