簡體   English   中英

將循環內的對象數組合並到新對象中

[英]Merge array of objects inside loop into new object

嘗試創建一個新對象,然后將來自 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 仍然是我正在學習和工作的語言,有些事情仍然讓我感到困惑。

謝謝你。

您可以使用Array.map()創建新數組,然后使用一些解構來創建此數組中的每個新元素。

我們通過首先映射子項數組以獲取子項名稱列表,然后使用Array.join()創建逗號分隔的字符串,在每個新元素上創建 allitems 屬性。

你看到的作為 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; }

既然只想更新現有的對象,就用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)

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

邏輯

  • 由於您想創建一個新數組, Array.map在父數組上運行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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM