【问题标题】:Mapping JavaScript Object Into An Array Of Hashes [duplicate]将 JavaScript 对象映射到哈希数组 [重复]
【发布时间】:2018-12-04 21:18:35
【问题描述】:

我想获取一个 Javascript 对象并将其转换为哈希数组。

以下方法仅获取对象的一个​​元素并将其转换为数组:

const coordinatesArray = items.map((item) => item.latitude)

返回:[51.5165328979492, 51.5990409851074, 51.5990409851074, 51.5165328979492, 51.5098190307617, 51.5128326416016, 51.5098190307617, 51.501766204834, 51.514087677002, 51.4983825683594, 51.5294952392578, 51.5123977661133, 51.5011863708496, 51.5204887390137, 51.514087677002, 51.5117797851562, 51.5139465332031]

但是当我尝试创建散列元素来组成数组时,我得到一个错误:

const coordinatesArray = items.map((item) => { x:item.latitude, y:item.longitude })

返回:Uncaught Error: Module build failed: SyntaxError: Unexpected token, expected ;

我做错了什么?

【问题讨论】:

    标签: javascript ecmascript-6


    【解决方案1】:

    尝试以下方法:

    const coordinatesArray = items.map((item) => ({ x:item.latitude, y:item.longitude }))
    

    返回对象的 Lambda 函数需要一个额外的括号集 () 来将它们与函数体区分开来。

    【讨论】:

    • 非常感谢。成功了!
    【解决方案2】:

    你需要在花括号周围加上一些括号,否则它会被解释为arrow functions中的块语句。

    const coordinatesArray = items.map((item) => ({ x: item.latitude, y: item.longitude }));
    

    具有解构和短属性的更短:

    const coordinatesArray = items.map(({ latitude: x, longitude: y }) => ({ x, y }));
    

    【讨论】:

    • 还有一个;最后不见了
    【解决方案3】:

    用括号括住函数体以返回对象文字表达式:

     params => ({foo: bar}) 
    

    在你的情况下:

    const coordinatesArray = items.map((item) => ({ x:item.latitude, y:item.longitude }))
    

    更多信息here.

    【讨论】:

      猜你喜欢
      • 2017-10-09
      • 2012-08-05
      • 2017-01-05
      • 1970-01-01
      • 2020-11-09
      • 2012-03-23
      • 2023-03-07
      • 1970-01-01
      • 2014-05-31
      相关资源
      最近更新 更多