2016-08-24 127 views
15

我敢肯定,这个问题以前有人问,但我不能完全找到我要找的答案,所以这里有云:合并两个对象ES6

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

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合并这两个对象的最佳方式?

+0

*“ES6推出了酷解构/分配的东西” *不与合并对象属性在所有帮助。 –

回答

30

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

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

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

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

 
console.log(newItem);

您还可以使用object spread,这是一个大舞台3提案的ECMAScript,并要求巴别塔的Object rest spread transform(包含在Stage 3 preset)使用方法:

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

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

 
const newItem = { ...item, location: response }; 
 

 
console.log(newItem);