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)
not*_*rgi 44
另一个方法是:
let result = { ...item, location : { ...response } }
Run Code Online (Sandbox Code Playgroud)
但对象传播尚未标准化.
也许有帮助:https://stackoverflow.com/a/32926019/5341953
归档时间: |
|
查看次数: |
88407 次 |
最近记录: |