使用ES6合并两个对象 [英] Merge two objects with ES6
问题描述
我确定之前已经问过这个问题,但我找不到我想要的答案,所以这里有:
I'm sure this question has been asked before but I can't quite find the answer I'm looking for, so here goes:
我有两个对象,如下:
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
}
}
我知道我可以这样做:
item.location = {}
item.location.lat = response.lat
item.location.lng = response.lng
然而,我觉得这不是最好的方法,因为ES6引入了c ool解构/分配东西;我尝试深度对象合并,但遗憾的是不支持:(我也查看了一些ramda函数,但看不到任何适用的东西。
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合并这两个对象?
So what is the best way to merge these two objects using ES6?
推荐答案
您可以使用 Object.assign()
将它们合并为一个新对象:
You can use Object.assign()
to merge them into a new object:
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 );
您还可以使用对象传播,这是第4阶段提案对于ECM AScript:
You can also use object spread, which is a Stage 4 proposal for 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 );
这篇关于使用ES6合并两个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!