【问题标题】:Merge array of objects inside loop into new object将循环内的对象数组合并到新对象中
【发布时间】:2021-12-14 06:54:48
【问题描述】:

尝试创建一个新对象,然后从 JSON 文件中的嵌套值连接所有对象。

JSON 数据比较大,所以拿了个样本,叫它 var items

我遇到的问题是嵌套数据没有更新新对象。

var items = [
    {
    "id": 11,
    "title": "Fruit Test",
    "releaseDateTime": "2021-10-21T10:50:00+09:30",
    "mainContent": "Fruit order for 1 person",
    "storeNames": [
        "Store 1"
    ],
    "items": [
        {
            "itemName": "Melon",
            "otherName": "Watermelon"
        },
        {
            "itemName": "Apple",
            "otherName": "Red apple"
        }
    ]

},
{
    "id": 12,
    "title": "Canned Test",
    "releaseDateTime": "2021-10-21T10:50:00+09:30",
    "mainContent": "Canned order for 2 people",
    "storeNames": [
        "Store 1"
    ],
    "items": [
        {
            "itemName": "Tomatoes",
            "otherName": "Diced tomato"
        }
    ]
},
{
    "id": 13,
    "title": "Dairy Test",
    "releaseDateTime": "2021-10-21T10:50:00+09:30",
    "mainContent": "Dairy Order for 2 people",
    "storeNames": [
        "Store 1"
    ],
    "items": []
}
]
;

var copyItems = [];


for (let i = 0; i < items.length; i++) {
items[i].allItems = items[i].items;
  copyItems.push(items[i])
}

console.log(copyItems);


var copyItems = copyItems.map(function(elem){
    return elem.allItems;
}).join(",");

console.log(`These are the final items ${copyItems}`);

我能够创建新对象,并将嵌套数组添加到其中。但是我试图让 allItems 对象显示如下信息:

[
    {
    "id": 11,
    "allItems": "Melon, Apple",
    "title": "Fruit Test",
    "releaseDateTime": "2021-10-21T10:50:00+09:30",
    "mainContent": "Fruit order for 1 person",
    "storeNames": [
        "Store 1"
    ],
    "items": [
        {
            "itemName": "Melon",
            "otherName": "Watermelon"
        },
        {
            "itemName": "Apple",
            "otherName": "Red apple"
        }
    ]

},
{
    "id": 12,
    "allItems": "Tomatoes",
    "title": "Canned Test",
    "releaseDateTime": "2021-10-21T10:50:00+09:30",
    "mainContent": "Canned order for 2 people",
    "storeNames": [
        "Store 1"
    ],
    "items": [
        {
            "itemName": "Tomatoes",
            "otherName": "Diced tomato"
        }
    ]
},
{
    "id": 13,
    "allItems": "",
    "title": "Dairy Test",
    "releaseDateTime": "2021-10-21T10:50:00+09:30",
    "mainContent": "Dairy Order for 2 people",
    "storeNames": [
        "Store 1"
    ],
    "items": []
}
]

这是我的 JSFiddle:https://jsfiddle.net/buogdvx9/6/

Javascript 仍然是我正在学习和使用的一门语言,但有些东西仍然让我很着迷。

谢谢。

【问题讨论】:

  • 请澄清一下,您希望得到哪种输出。一些例子会很好。
  • 不清楚预期的输出是什么。您的代码似乎针对 one 字符串输出,列出所有项目名称。但是随后您为我们提供了一个具有附加属性的对象数组。不清楚你想要哪两个。

标签: javascript arrays json object


【解决方案1】:

由于您只想更新现有对象,因此使用forEach 循环遍历数组中的每个项目,然后使用map 运算符循环遍历繁荣以获取带有itemName 的数组。

  items.forEach((obj) => {
      
      obj.allItems = obj.items.map((item) => item.itemName)
    });
    
    console.log(items)

简单示例:

   // iterating over the items
 for (let i = 0; i < items.length; i++) {
  
    let currentItem = items[i];
  
    currentItem.allItems = []; // adding new empty array
  
    for (let j = 0; j < currentItem.items.length; j++) {
      
        currentItem.allItems.push(currentItem.items[j].itemName);
    }

}

工作示例:

var items = [
    {
    "id": 11,
    "title": "Fruit Test",
    "releaseDateTime": "2021-10-21T10:50:00+09:30",
    "mainContent": "Fruit order for 1 person",
    "storeNames": [
        "Store 1"
    ],
    "items": [
        {
            "itemName": "Melon",
            "otherName": "Watermelon"
        },
        {
            "itemName": "Apple",
            "otherName": "Red apple"
        }
    ]

},
{
    "id": 12,
    "title": "Canned Test",
    "releaseDateTime": "2021-10-21T10:50:00+09:30",
    "mainContent": "Canned order for 2 people",
    "storeNames": [
        "Store 1"
    ],
    "items": [
        {
            "itemName": "Tomatoes",
            "otherName": "Diced tomato"
        }
    ]
},
{
    "id": 13,
    "title": "Dairy Test",
    "releaseDateTime": "2021-10-21T10:50:00+09:30",
    "mainContent": "Dairy Order for 2 people",
    "storeNames": [
        "Store 1"
    ],
    "items": []
}
]
;
// since you only want to update the existing object, using map to loop over each item in array
items.forEach((obj) => {
  // using map to create the new array of just itemNames
  obj.allItems = obj.items.map((item) => item.itemName)
});

console.log(items)

【讨论】:

    【解决方案2】:

    您可以使用Array.map() 创建新数组,然后使用一些destructuring 在此数组中创建每个新元素。

    我们在每个新元素上创建 allitems 属性,首先映射子项数组以获取子项名称列表,然后使用Array.join() 创建一个逗号分隔的字符串。

    您看到的arrow function 作为 Array.map 的第一个参数是另一种编写 function(args) { .. } 的方式。

    const items = [ { "id": 11, "title": "Fruit Test", "releaseDateTime": "2021-10-21T10:50:00+09:30", "mainContent": "Fruit order for 1 person", "storeNames": [ "Store 1" ], "items": [ { "itemName": "Melon", "otherName": "Watermelon" }, { "itemName": "Apple", "otherName": "Red apple" } ]  }, { "id": 12, "title": "Canned Test", "releaseDateTime": "2021-10-21T10:50:00+09:30", "mainContent": "Canned order for 2 people", "storeNames": [ "Store 1" ], "items": [ { "itemName": "Tomatoes", "otherName": "Diced tomato" } ] }, { "id": 13, "title": "Dairy Test", "releaseDateTime": "2021-10-21T10:50:00+09:30", "mainContent": "Dairy Order for 2 people", "storeNames": [ "Store 1" ], "items": [] } ];
    
    const result = items.map(({ id, ...rest}) => { 
        return { 
          id,
          allItems: rest.items.map(el => el.itemName).join(', '), 
          ...rest
        };
    });
    
    console.log(result)
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 感谢您的快速回复。这正是我所追求的。这可能要求太多了,但是因为我还在学习,所以 JS 中的箭头对我来说还是有点难以理解。是否有可能将其分解,以便我了解您是如何得出结果的?并尝试与我创建的其他示例相同?无论哪种方式,您的帮助都非常感谢。
    • 哦,是的。我会更新答案!
    【解决方案3】:

    只需使用Array.mapArray.join 的组合

    逻辑

    • 由于要创建新数组,请在父数组上运行 Array.map
    • 在父节点的每个节点上,使用一个额外的键 allItems 返回整个节点。
    • 对于allItems,在每个节点中从items 数组创建一个新数组,然后用空格连接

    var items = [{"id":11,"title":"Fruit Test","releaseDateTime":"2021-10-21T10:50:00+09:30","mainContent":"Fruit order for 1 person","storeNames":["Store 1"],"items":[{"itemName":"Melon","otherName":"Watermelon"},{"itemName":"Apple","otherName":"Red apple"}]},{"id":12,"title":"Canned Test","releaseDateTime":"2021-10-21T10:50:00+09:30","mainContent":"Canned order for 2 people","storeNames":["Store 1"],"items":[{"itemName":"Tomatoes","otherName":"Diced tomato"}]},{"id":13,"title":"Dairy Test","releaseDateTime":"2021-10-21T10:50:00+09:30","mainContent":"Dairy Order for 2 people","storeNames":["Store 1"],"items":[]}];
    const newItems = items.map(node => ({ ...node, allItems: node.items.map(item => item.itemName).join(" ")}));
    console.log(newItems);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-13
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 2020-01-28
      • 2017-06-11
      • 1970-01-01
      相关资源
      最近更新 更多