我有兩個陣列,陣列 1 包含部分,陣列 2 包含物件,目標是根據型別(面或醬)將物件內的陣列 2 中的物件插入到 Array1 中,例如:來自陣列的每個物件2 包含的元素type:Sauces應設定在陣列 1 的物件內的陣列中type:Sauces,以此類推。我嘗試使用該forEach函式,但由于我對 JavaScript 比較陌生,我不知道如何繼續
陣列 1(部分)
Array [
Object {
"required": false,
"type": "Sides",
},
Object {
"required": true,
"type": "Sauces",
},
]
陣列 2(物件串列)
Array [
Object {
"id": 2.01,
"price": "1",
"title": "Hot Sauce",
"type": "Sauces",
},
Object {
"id": 2.02,
"price": 1,
"title": "Medium Sauce",
"type": "Sauces",
},
Object {
"id": 1.01,
"price": 1,
"title": "Ranch",
"type": "Sides",
},
Object {
"id": 1.02,
"price": 1,
"title": "Blue Cheese",
"type": "Sides",
},
]
這就是我想要實作的目標:
Array [
Object {
"required": false,
"type": "Sides",
"data": [
Object {
"id": 1.01,
"price": 1,
"title": "Ranch",
"type": "Sides",
},
Object {
"id": 1.02,
"price": 1,
"title": "Blue Cheese",
"type": "Sides",
},
]
},
Object {
"required": true,
"type": "Sauces",
"data":[
Object {
"id": 2.01,
"price": "1",
"title": "Hot Sauce",
"type": "Sauces",
},
Object {
"id": 2.02,
"price": 1,
"title": "Medium Sauce",
"type": "Sauces",
},
]
},
]
uj5u.com熱心網友回復:
這應該適合你:
arr1.forEach((a,i) => {
a["data"] = arr2.filter(b => b.type == a.type);
})
uj5u.com熱心網友回復:
我命名 Array1 = 類別 我命名 Array2 = 元素 您需要在每個上進行映射。
const test = categories.map((cat) => {
elements.map((el) => {
if (el.type === cat.type) {
cat.elements.push(el);
}
return el;
});
return cat;
});
console.log(test);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/426583.html
標籤:javascript 数组 反应式 排序 前锋
下一篇:這兩個箭頭函式有什么區別?
