使用ES6合并两个对象

Tom*_*ley 85 javascript ecmascript-6

我确定之前已经问过这个问题,但我找不到我想要的答案,所以这里有:

我有两个对象,如下:

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

let item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK'
}
Run Code Online (Sandbox Code Playgroud)

我需要将这些合并在一起形成:

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

我知道我可以这样做:

item.location = {}
item.location.lat = response.lat
item.location.lng = response.lng
Run Code Online (Sandbox Code Playgroud)

但是,我觉得这不是最好的方法,因为ES6引入了很酷的解构/分配东西; 我尝试深度对象合并,但遗憾的是不支持:(我也查看了一些ramda函数,但看不到任何适用的东西.

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

Ori*_*ori 135

您可以使用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 );
Run Code Online (Sandbox Code Playgroud)

您还可以使用object spread,这是ECMAScript的第4阶段提案:

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 );
Run Code Online (Sandbox Code Playgroud)

  • 如果你做`const newItem = {... item,location:response};`,请注意`newItem`的`location`属性是对`response`对象的引用.你最好像`const newItem = {... item,location:{... response}};`来避免引用和安全. (5认同)

not*_*rgi 44

另一个方法是:

let result = { ...item, location : { ...response } }
Run Code Online (Sandbox Code Playgroud)

但对象传播尚未标准化.

也许有帮助:https://stackoverflow.com/a/32926019/5341953

  • 通过这种方式,响应保存为指针而不是深度克隆.这应该是正确答案`let result = {... item,location:{... response}}` (3认同)