gpt4 book ai didi

javascript - 如何按键合并两个对象数组并将合并的数据放入子数组中

转载 作者:行者123 更新时间:2023-12-02 21:20:59 25 4
gpt4 key购买 nike

我将使用什么工具通过主对象上的键将新对象合并到子数组中?让我告诉你我的意思:

我有这个对象,它是对象数组中的一个示例:

array1 = [{
"employeeId": 1,
"registerID": 1,
"shopID": 1,
"completed": true,
"completeTime": "06/04/2017",
"referenceNumber": 10001000152,
"referenceNumberSource": "epos",
"SaleLines": {
"SaleLine": [
{
"itemID": "JRY",
"unitQuantity": 1,
"ItemDescription": "EXPRESS STUFF",
"Supplier": "JR(Wholesale) Ltd",
"Cost": 2.52,
"Price": 5.99,
"Tax": 1,
"TotalSales": 6.99
},
{
"itemID": "2HANDGOODS",
"unitQuantity": 1,
"ItemDescription": "SECONDHAND GOODS",
"Supplier": "Some Stuff Limited",
"Cost": 0,
"Price": 240,
"Tax": 0,
"TotalSales": 240
}
]
}
}]

我有另一个对象数组,我已将其过滤为以下内容,例如:

array2 = [{ItemID:'5101', systemSku:'JRY'}, {ItemID:'5102', systemSku:'2HANDGOODS'}]

我想要实现的目标是使用 array2 中的 systemSku 来匹配 array1 中的 itemID 并将 ItemID 作为 itemID 的值并将 systemSku 添加到 SaleLine 对象。Array1 和 Array2 都包含大约 5200 个对象。

因此 array1 上 SaleLines 中的 SaleLine 看起来像:

{
"ItemID": "5101"
"systemSku": "JRY",
"unitQuantity": 1,
"ItemDescription": "EXPRESS STUFF",
"Supplier": "JR(Wholesale) Ltd",
"Cost": 2.52,
"Price": 5.99,
"Tax": 1,
"TotalSales": 6.99
}

我在想一些类似的事情:

for (item in newItemsObject) {
for (sale in sales) {
if (item.itemID === sale.systemSku) {
return newObjects = {
itemID: item.itemID,
systemSku: item.systemSku,
completeTime: sales.completeTime
}
}
console.log(newObjects)
}}

但这不起作用。

最佳答案

请尝试以下操作:

let array1 = [{
"employeeId": 1,
"registerID": 1,
"shopID": 1,
"completed": true,
"completeTime": "06/04/2017",
"referenceNumber": 10001000152,
"referenceNumberSource": "epos",
"SaleLines": {
"SaleLine": [
{
"itemID": "JRY",
"unitQuantity": 1,
"ItemDescription": "EXPRESS STUFF",
"Supplier": "JR(Wholesale) Ltd",
"Cost": 2.52,
"Price": 5.99,
"Tax": 1,
"TotalSales": 6.99
},
{
"itemID": "2HANDGOODS",
"unitQuantity": 1,
"ItemDescription": "SECONDHAND GOODS",
"Supplier": "Some Stuff Limited",
"Cost": 0,
"Price": 240,
"Tax": 0,
"TotalSales": 240
}
]
}
}];
let array2 = [{ItemID:'5101', systemSku:'JRY'}, {ItemID:'5102', systemSku:'2HANDGOODS'}];

array1 = array1.map(function (item1) {
item1['SaleLines']['SaleLine'] = item1['SaleLines']['SaleLine'].map(function (innerItem) {
array2.map(function (item2) {
if(item2.systemSku == innerItem.itemID){
innerItem['itemID'] = item2['ItemID'];
innerItem['systemSku'] = item2['systemSku'];
}
});
return innerItem
});
return item1
});
console.log(array1);

关于javascript - 如何按键合并两个对象数组并将合并的数据放入子数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60846480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com