简体   繁体   English

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

[英]How to append an object to each item in an array

I am trying to append an object to an array, but cart[i]['items'][j][order] is not getting set properly.我正在尝试将一个对象附加到一个数组中,但是cart[i]['items'][j][order]没有正确设置。

When logging cart[i]['order'] it returns an Object .当记录cart[i]['order']它返回一个Object

The cart is of the form:购物车的形式为:

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

Expected Result预期结果

[{
  "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": "" }
}]

Code代码

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]);
  }
}

Alternate Attempt替代尝试

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]

How can I add this object to each cart[i]['items'][j] element?如何将此对象添加到每个cart[i]['items'][j]元素?

You code generate a error on push of cart[i]['items'][j].push(...) remove a [j]您的代码在推车时生成错误cart[i]['items'][j].push(...)删除[j]

Try this:尝试这个:

 let carts = [{ order: { amtSubTotal: 3812.8900000000003, noPo: "Default PO" }, 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);

try this pen试试这支笔

Use map() to modify your object on each iteration and to add items object's properties iterate through key values for(let [key, value] of Object.entries(itemObj)使用 map() 在每次迭代时修改您的对象,并添加 items 对象的属性迭代通过键值for(let [key, value] of Object.entries(itemObj)

Try running this snippet.尝试运行此代码段。 Ive added second item in cart for testing purpose我在购物车中添加了第二个项目以进行测试

 let cart=[{"order": {"amtSubTotal": 3812.8900000000003,"noPo": "Default PO"},"items": [{"adjustments": { "isCustom": "N" }, "lineNote": { "noteLine": "" }},{"adjustments": { "isCustom": "N" }, "lineNote": { "noteLine": "" }}]},{"order": {"amtSubTotal": 3112.8900000000003,"noPo": "Default RO"},"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[key]=value; }); return obj }); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

You can try with destructuring and map as below.您可以尝试如下解构和映射。 (In the arrow function argument, destructure order and items , use map to over items and add the contents of order.) (在箭头函数参数中,解构orderitems ,使用map覆盖 items 并添加 order 的内容。)

 const update = ([{ order, items }]) => items.map(itm => ({ order: {...order}, ...itm })); const data = [ { order: { amtSubTotal: 3812.8900000000003, noPo: "Default PO" }, items: [ { adjustments: { isCustom: "N" }, lineNote: { noteLine: "" } }, { adjustments: { isCustom: "N" }, lineNote: { noteLine: "" } } ] } ]; console.log(update(data));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM