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

标签 javascript ecmascript-6

我目前正在使用以下代码,从 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/

相关文章:

javascript - 字节数组到 Uint64 作为字符串

javascript - 根据对象的值将javascript对象键排序到数组中

javascript - 在 Adonis Lucid 子查询上选择 JSON 字段键

JavaScript 部分匹配数组中的字符串

AngularJS 2.0 编译成 ES6

Javascript:处理常量和跨浏览器兼容性

javascript - 如何在 React-quill 中添加自定义字体大小

javascript - 使用 JQuery 并考虑子 JSON 对象将表单解析为 JSON 对象

javascript - addEventListener 和单击按钮上的 if 语句

javascript - 正则表达式用数字检查模式