2016-08-24 146 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);