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

标签 javascript ecmascript-6

我想使用扩展运算符合并两个 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/

相关文章:

javascript - SonarQube 分析在 ES2015 语法上失败——但显然支持它?

javascript - 单击日期时,AngularJS DatePicker 不更新值

javascript - 在移动视口(viewport)中,如何阻止 bootstrap 4 导航栏粘在页面顶部?

javascript - jQuery 文档就绪调用序列

javascript - 将 php 变量传递给按钮 onclick 函数

javascript - 将现有函数声明为异步?

Javascript 将数组连接到字符串

javascript - ECMAScript 6 中的 Symbol.for(string)

javascript - 在 JavaScript 中使用赋值进行选择性对象解构?

javascript - 将逻辑应用于 defaultProps