gpt4 book ai didi

javascript - 如何简化 ES6 中的对象映射?

转载 作者:行者123 更新时间:2023-11-29 17:51:06 25 4
gpt4 key购买 nike

我目前正在使用以下代码,从 action.payload 中获取一些属性并分配给对象 weather

我想知道在 ES6 中是否有更优雅、更简洁的方式来做同样的操作。

let weather = {}
weather.name = action.payload.name
weather.country = action.payload.sys.country
weather.temperature = action.payload.main.temp
weather.temperatureMin = action.payload.main.temp_min
weather.temperatureMax = action.payload.main.temp_max
weather.weatherMain = action.payload.weather[0].main
weather.weatherDescription = action.payload.weather[0].description
weather.weatherIcon = action.payload.weather[0].icon
weather.updatedTime = new Date().toString()
weather.windDegree = action.payload.wind.deg
weather.windSpeed = action.payload.wind.speed
weather.visibility = action.payload.visibility

最佳答案

这里没有特定的语言级魔法。您正在从多个级别的 action 对象中拉取,并即时重命名许多属性。如果名称保持不变,对象解构和结构分配可能会彻底解决问题。但就目前而言,您可以获得的最大清晰度是不重复那么多名称。例如:

let payload = action.payload
let weather = {
name: payload.name,
country: payload.sys.country,
temperature: payload.main.temp,
temperatureMin: payload.main.temp_min,
temperatureMax: payload.main.temp_max,
weatherMain: payload.weather[0].main,
weatherDescription: payload.weather[0].description,
weatherIcon: payload.weather[0].icon,
updatedTime: new Date().toString(),
windDegree: payload.wind.deg,
windSpeed: payload.wind.speed,
visibility: payload.visibility
}

作为此作业的一部分,当然可以使用更多 ES2015 解构功能。例如:

const { payload } = action
const { main, weather, wind, sys } = payload
let weather = {
name: payload.name,
country: sys.country,
temperature: main.temp,
temperatureMin: main.temp_min,
temperatureMax: main.temp_max,
weatherMain: weather[0].main,
weatherDescription: weather[0].description,
weatherIcon: weather[0].icon,
updatedTime: new Date().toString(),
windDegree: wind.deg,
windSpeed: wind.speed,
visibility: payload.visibility
}

我一般推荐这进一步的步骤。在我看来,这并不一定能让事情变得更清楚。至少,需要权衡取舍。原始对象与其多层次结构之间的自然对应关系变得更加隐蔽;需要记住和解释子对象的起源,例如 windweathermainsys。但从好的方面来说,它在 ES2015 的使用中更简洁也更积极。您必须判断这是更好还是更漂亮。

关于javascript - 如何简化 ES6 中的对象映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43708503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com