如何將一個陣列中的值添加到另一個陣列中以創建新陣列?
我有兩個陣列,我想通過 arrayTwo 過濾從arrayOne中找到哪里。然后從arrayOne添加到arrayTwo ,這樣我就可以得到一個結果,比如arrayThreeid === productIDquantity
arrayOne = [
{
productID: "DuWTLdYkpwF1DJ2x8SGB",
quantity: 2
},
]
arrayTwo = [
{
id: "DuWTLdYkpwF1DJ2x8SGB",
minQuantity: 1,
name: "5 Shade Palette",
price: "950",
size: "30g",
unitPrice: 950,
},
]
想要的結果::
arrayThree = [
{
id: "DuWTLdYkpwF1DJ2x8SGB",
minQuantity: 1,
name: "5 Shade Palette",
price: "950",
size: "30g",
unitPrice: 950,
quantity: 2,
},
]
uj5u.com熱心網友回復:
您可以使用擴展運算子輕松合并這兩個物件:
arrayOne = [
{
productID: "DuWTLdYkpwF1DJ2x8SGB",
quantity: 2
},
]
arrayTwo = [
{
id: "DuWTLdYkpwF1DJ2x8SGB",
minQuantity: 1,
name: "5 Shade Palette",
price: "950",
size: "30g",
unitPrice: 950,
},
]
console.log({...arrayOne[0], ...arrayTwo[0]})
將此與您的初始過濾器結合使用,您應該擁有您想要的。但是,我建議改用“find()”。
傳播
尋找
uj5u.com熱心網友回復:
這里的時間復雜度為 O(n^2)。如果給定的陣列真的很長,則不是最佳選擇。基本上:對于 中的每個專案,在其中arrayOne找到它的對arrayTwo并將它們合并。
let arrayThree = arrayOne.map(first => {
return {
...first,
...arrayTwo.find(second => second.id == first.productID)
}
});
uj5u.com熱心網友回復:
以下是實作目標的一種可能方式。
代碼片段
// add "quantity" to existing products
const addDeltaToBase = (delta, base) => (
// iterate over the "base" (ie, existing product array)
base.map(
({ id, ...rest }) => { // de-structure to access "id"
// check if "id" is part of the delta (to update "quantity")
const foundIt = delta.find(({ productID }) => productID === id);
if (foundIt) { // found a match, so update "quantity
return ({
id, ...rest, quantity: foundIt.quantity
})
};
// control reaches here only when no match. Return existing data as-is
return { id, ...rest }
}
) // implicit return from "base.map()"
);
const arrayOne = [
{
productID: "DuWTLdYkpwF1DJ2x8SGB",
quantity: 2
},
];
const arrayTwo = [
{
id: "DuWTLdYkpwF1DJ2x8SGB",
minQuantity: 1,
name: "5 Shade Palette",
price: "950",
size: "30g",
unitPrice: 950,
},
];
console.log(addDeltaToBase(arrayOne, arrayTwo));
.as-console-wrapper { max-height: 100% !important; top: 0 }
解釋
在上面的代碼段中添加了行內注釋。
筆記
- 這個答案將能夠同時處理多個物件
arrayOne。arrayTwo - 它將 the
productId與 theid匹配,并且當匹配時,它將 the 合并quantity到輸出中(即arrayThree)。 - 它的目標是不可變的,因此輸入陣列可以保持原樣
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464693.html
標籤:javascript 数组 反应 反应式
