如何将对象附加到数组中的每个项目上

问题描述 投票:0回答:2

我正在尝试将对象附加到数组,但cart[i]['items'][j][order]设置不正确。

登录cart[i]['order']时返回Object

购物车的形式:

[{
  "order": {
    "amtSubTotal": 3812.8900000000003,
    "noPo": "Default P.O."
  },
  "items": [{
    "adjustments": { "isCustom": "N" }, 
    "lineNote": { "noteLine": "" }
  },{
    "adjustments": { "isCustom": "N" }, 
    "lineNote": { "noteLine": "" }
  }]
}]

预期结果

[{
  "order": { "amtSubTotal": 3812.8900000000003,"noPo": "Default P.O." },
  "adjustments": { "isCustom": "N" }, 
  "lineNote": { "noteLine": "" }
  }, {
  "order": { "amtSubTotal": 3812.8900000000003,"noPo": "Default P.O." },
  "adjustments": { "isCustom": "N" }, 
  "lineNote": { "noteLine": "" }
}]

代码

let cart = JSON.parse(localStorage.getItem('cart-data'));
let i = 0, j = 0, l = cart.length;
let nData = [];
for (i = 0; i < l; i++) {
  let m = cart[i]['items'].length;
  for (j = 0; j < m; j++) {                                                      // Spreading data {...data[i]} created a shallow copy bug
    cart[i]['items'][j].push({"order": cart[i]['order']}); // Try using JSON methods instead
    nData.push(cart[i]['items'][j]);
  }
}

其他尝试

for (i = 0; i < l; i++) {
  let m = cart[i]['items'].length;
  for (j = 0; j < m; j++) {
    // cart[i]['items'][j]['order'] = JSON.stringify(JSON.parse(cart[i]['order'])); // Try using JSON methods instead
    nData.push(cart[i]['items'][j]);
  }
}

console.log(nData); // order data not appended to cart[i]['items'][j]

如何将该对象添加到每个cart[i]['items'][j]元素?

javascript arrays push
2个回答
0
投票

您的代码在按下cart[i]['items'][j].push(...)时产生错误,删除[j]

尝试一下:

let carts = [{
  order: {
    amtSubTotal: 3812.8900000000003,
    noPo: "Default P.O."
  },
  items: [{
    adjustments: { "isCustom": "N" }, 
    lineNote: { "noteLine": "" }
  },{
    adjustments: { "isCustom": "N" }, 
    lineNote: { "noteLine": "" }
  }]
}];

nData = [];

carts.forEach((cart, idx1) => {
  cart['items'].forEach((item, idx2) => {
    item.order = cart.order;
    nData.push(item)
  })
});

console.log(nData);

0
投票

使用map()在每次迭代中修改您的对象并添加items对象的属性遍历键值for(let [key, value] of Object.entries(itemObj)

尝试运行此代码段。Ive在购物车中添加了第二项用于测试

let cart=[{"order": {"amtSubTotal": 3812.8900000000003,"noPo": "Default P.O."},"items": [{"adjustments": { "isCustom": "N" }, "lineNote": { "noteLine": "" }},{"adjustments": { "isCustom": "N" }, "lineNote": { "noteLine": "" }}]},{"order": {"amtSubTotal": 3112.8900000000003,"noPo": "Default R.O."},"items": [{"adjustments": { "isCustom": "Y" }, "lineNote": { "noteLine": "1" }},{"adjustments": { "isCustom": "N" }, "lineNote": { "noteLine": "5" }}]}]
let result=cart.map( orderObj =>
{ let obj={order:orderObj.order};
orderObj.items.forEach( itemObj =>
{for(let [key, value] of Object.entries(itemObj))
obj.order[key]=value;
});
return obj}); 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
© www.soinside.com 2019 - 2024. All rights reserved.