Javascript 用 ES6 合并两个对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39121695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:13:28  来源:igfitidea点击:

Merge two objects with ES6

javascriptecmascript-6

提问by Tom Oakley

I'm sure this question has been asked before but I can't quite find the answer I'm looking for, so here goes:

我确定这个问题以前有人问过,但我找不到我正在寻找的答案,所以这里是:

I have two objects, as follows:

我有两个对象,如下:

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

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

I need to merge these together to form this:

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

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

I know I could do it like this:

我知道我可以这样做:

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

However, I feel that this is not the best way to do it anymore, because ES6 introduced the cool destructuring/assignment stuff; I tried deep object merging but it's unfortunately not supported :( I also looked through some ramda functions but couldn't see anything that was applicable.

然而,我觉得这不再是最好的方法了,因为 ES6 引入了很酷的解构/赋值的东西;我尝试了深度对象合并,但不幸的是它不受支持:( 我还查看了一些 ramda 函数,但看不到任何适用的内容。

So what is the best way to merge these two objects using ES6?

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

回答by Ori Drori

You can use Object.assign()to merge them into a new object:

您可以使用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 );

You can also use object spread, which is a Stage 4 proposal for ECMAScript:

您还可以使用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 );

回答by notgiorgi

Another aproach is:

另一种方法是:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

但是对象传播还没有标准化

May also be helpful: https://stackoverflow.com/a/32926019/5341953

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