gpt4 book ai didi

javascript - Es6 使用扩展合并两个对象不起作用

转载 作者:行者123 更新时间:2023-11-28 14:17:02 25 4
gpt4 key购买 nike

我想使用扩展运算符合并两个 javascript 对象,但我无法产生预期的结果。这是我的第一个对象列表(包裹在对象内的对象)

var arr2 = {
"20080": {
"ProductQuantitesId": 20080,
"CustomerPrice": 100,
"DisplayQuantity": "20 L",
"DisplayProductName": "Bisleri Mineral Water",
"DiscountedPrice": 20,
"DiscountedPercentage": 17
},
"20110": {
"ProductQuantitesId": 20110,
"CustomerPrice": 270,
"DisplayQuantity": "5 kgs",
"DisplayProductName": "Srujana Curd Bucket",
"DiscountedPrice": 30,
"DiscountedPercentage": 10
} }

第二个对象列表是

var arr3 = {
"20080": {
"Qty": 2,


},
"20110": {
"Qty": 3,
} }

我想使用 es6 spread 合并这 2 个对象。

const result = {...arr2,...arr3}

期望将数量添加到对象中,但我只看到数量。我得到的结果

{
"20080": {
"Qty": 2
},
"20110": {
"Qty": 3
}
}

有人可以帮忙吗?

最佳答案

arr3 正在覆盖 arr2 中的值,因为两个对象共享相同的键。假设arr2arr3的 key 相同,您可以使用以下解决方案:

<小时/>

var arr2 = {
"20080": {
"ProductQuantitesId": 20080,
"CustomerPrice": 100,
"DisplayQuantity": "20 L",
"DisplayProductName": "Bisleri Mineral Water",
"DiscountedPrice": 20,
"DiscountedPercentage": 17
},
"20110": {
"ProductQuantitesId": 20110,
"CustomerPrice": 270,
"DisplayQuantity": "5 kgs",
"DisplayProductName": "Srujana Curd Bucket",
"DiscountedPrice": 30,
"DiscountedPercentage": 10
}
}

var arr3 = {
"20080": {
"Qty": 2,
},
"20110": {
"Qty": 3,
}
}

// First, get the keys from arr2 using Object.keys().
// Then, use Array.prototype.reduce() to iterate through the keys.
// In the callback, acc is referring to the empty object, {},
// passed as the second argument in reduce().
const result = Object.keys(arr2).reduce((acc, key) => {

// Set the value of the resulting object's key equal to the
// combined key-values of arr2 and arr3
acc[key] = { ...arr2[key], ...arr3[key] }

// Make sure to return the object
return acc
}, {})

console.log(result)

关于javascript - Es6 使用扩展合并两个对象不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57016150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com