我想在依赖于json数据ID的两个不同的json数组上合并相同的特定json对象。
JSON数据集1
{
"Product":[
{
"product_id": "123",
"location_id": "222",
"product_code": "abc",
},
{
"product_id": "456",
"location_id": "111",
"product_code": "xyz",
}
]
}
JSON数据集2
{
"Location":[
{
"location_id": 111,
"location_name": "alpha"
},
{
"location_id": 222,
"location_name": "tango"
}
]
}
结果将是这样的
{
"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"
}
]
}
到目前为止,这是我完成的代码。
var finalJson = {};
_.each(_.keys(productArray,locationArray), function(key) {
finalJson[key] = _.flatten(_.zip(productArray[key], locationArray[key]));
});
console.log(finalJson);
最佳答案
一个简单的算法可以使用嵌套循环遍历两个数组,如下所示:
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);