ES6如何合并两个对象

121

我敢肯定这个问题以前已经有人问过了,但我找不到我想要的答案,所以在这里问一下:

我有两个对象,如下所示:

const response = {
  lat: -51.3303,
  lng: 0.39440
}

let item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK'
}

我需要将它们合并在一起,形成这样的结果:

item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK',
  location: {
    lat: -51.3303,
    lng: 0.39440
  }
}

我知道我可以这样做:

item.location = {}
item.location.lat = response.lat
item.location.lng = response.lng

然而,我认为这不再是最好的方法,因为ES6引入了很酷的解构/赋值语法;我尝试过深度对象合并,但不幸的是它不支持 :( 我还查看了一些Ramda函数,但没有找到适用的东西。

那么,使用ES6合并这两个对象的最佳方法是什么?


1
ES6引入了很酷的解构/赋值语法,但这对于合并对象属性没有任何帮助。 - Felix Kling
2个回答

181

你可以使用 Object.assign() 将它们合并为一个新对象:

const response = {
  lat: -51.3303,
  lng: 0.39440
}

const item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK'
}

const newItem = Object.assign({}, item, { location: response });

console.log(newItem );

你还可以使用 对象展开,这是一项针对 ECMAScript 的第四阶段提议:

const response = {
  lat: -51.3303,
  lng: 0.39440
}

const item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK'
}

const newItem = { ...item, location: response }; // or { ...response } if you want to clone response as well

console.log(newItem );


21
如果你执行 const newItem = { ...item, location: response };,请小心,因为 newItem 对象中的 location 属性会引用 response 对象。最好这样写 const newItem = { ...item, location: {...response} };,以避免引用和安全。 - hswner
Object.assign 对我有用..谢谢。 - Hugo Leonardo

74
另一种方法是:
let result = { ...item, location: { ...response } }

但是对象展开(Object spread)还没有标准化。
可能也会有帮助:https://dev59.com/SlwY5IYBdhLWcg3wK1L-#32926019

5
以这种方式,响应被保存为指针而不是深层克隆。这应该是正确的答案:let result = { ...item, location: {...response} } - FisNaN

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接