我试图使我的代码尽可能干净,我想解构并使其成为一行/更短。我不喜欢我data.id在对象中一遍又一遍地写。let { data } = await api.getCity(cityName, units) // database call
data = {id: data.id, name: data.name, country: data.sys['country'], main: data.main, weather: data.weather[0]}谢谢你!
3 回答
扬帆大鱼
TA贡献1799条经验 获得超9个赞
你可以这样做
...
const data = await api.getCity(cityName, units)
const {id, name, sys, main} = data
let newData = {id, name, sys}
...
小唯快跑啊
TA贡献1863条经验 获得超2个赞
我怀疑这会显着提高可读性;无论如何,这是单行解构:
let { data: {id, name, main, sys:{ country }, weather: [weather] }} = await api.getCity(cityName, units) // database call
const mockData = {
data: {
id: '1',
name: 'john',
main: 'something',
sys: {
country: 'International',
foo: 'bar'
},
weather: ['city1-rainy', 'city2-sunny']
}
};
let { data: {id, name, main, sys:{ country }, weather: [weather] }} = mockData;
console.log('id', id)
console.log('name', name)
console.log('main', main)
console.log('country', country)
console.log('weather', weather)
阿波罗的战车
TA贡献1862条经验 获得超6个赞
由于您只是修改国家和天气,您可以执行以下操作:
let { data } = await api.getCity(cityName, units) // database call data = {...data, country: data.sys['country'], weather: data.weather[0]}
添加回答
举报
0/150
提交
取消