[英]How can I concat an array to an array that is inside an array of objects?
我正在嘗試將一個數組連接到對象數組中的一個數組( productsCategories
)。
因此,這是productCategories
數組的樣子:
[
{
id: 123,
items: [ { Obj1 }, { Obj2 } ]
},
{
id:456,
items: [ { Obj1 }, { Obj2 } ]
}
]
我有一些新數組,例如[ { Obj3 }, { Obj4 } ]
,我想將其concat
到id = 123
的對象的productCategories
。
為此,
我首先使用lodash的find
來找到要更新的正確對象,並使用concat
將兩個數組連接在一起:
let nextItems:any = find(productCategories, { id: payload.id });
nextItems = assign({}, nextItems, { items: nextItems.items.concat(payload.items)});
因此, nextItems.items
具有串聯的項數組。
但是,現在我很難將其添加到productCategories
數組中。 我需要找到id
與nextItems.id
相同的對象,然后將productCategories.items
設置為nextItems.items
。
正確的方法是什么?
在nextItems.id
中找到與productCategories
匹配的對象的索引,然后為其分配新的串聯數組。 您可以使用lodash的findIndex()方法查找與id匹配的對象的索引。
var index = _findIndex(productCategories, { id: nextItems.id });
productCategories[index].items = nextItems.items;
您也可以使用純JavaScript。 使用ES6傳播語法,它看起來可能像這樣:
productCategories.filter(x => x.id == payload.id)
.forEach(x => x.items.push(...payload.items));
這是帶有示例數據的代碼段:
// Sample data var productCategories = [{ id: 123, items: [ { a: 1 }, { a: 2 } ] }, { id: 456, items: [ { b: 1 }, { b: 2 } ] }]; var payload = { id: 123, items: [ { c: 1 }, { c: 2 } ] }; // Update with payload productCategories.filter(x => x.id == payload.id) .forEach(x => x.items.push(...payload.items)); // Show results console.log(productCategories);
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.