【问题标题】:return object from array map从数组映射返回对象
【发布时间】:2019-07-06 15:43:12
【问题描述】:

假设我可以硬编码以下内容:

const data = [ { a: 0, b: 1}, {a:2,b:3},... ]

但我有一个数组中的数据,我想写如下内容:

const data = my_arr.map((element,index) => { a:element, b:index});

如何从数组映射中产生这种对象?

【问题讨论】:

    标签: javascript arrays dictionary object


    【解决方案1】:

    您只需要在返回的对象字面量周围添加括号。

    const my_arr = [1,2,3,4,5];
    const data = my_arr.map((element, index) => ({ a: element, b:index }));
    //                                          ^                       ^    
    
    console.log(data);

    原因是 JavaScript 解析器规则假定 { 跟在 => 之后是函数体的开始。为了解决这个问题,我们将对象包装在 () 中(或者我们可以添加 return 语句)

    在此处阅读更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Returning_object_literals

    【讨论】:

      【解决方案2】:

      啊,想通了。

      匿名对象与作用域运算符发生冲突,因此需要将对象封装在作用域块中,并从那里通过返回传递对象:

      const data = my_arr.map((element,index) => { return {a:element,b:index}});
      

      【讨论】:

      • 您可以通过用括号括起来大括号来做同样的事情。 .map((element,index) => ({a:element,b:index}))
      【解决方案3】:

      您必须在返回的对象周围添加括号,以将其与简单的块区分开来:

      const my_arr = [1, 2, 4, 3, 4];
      const data = my_arr.map((element, index) => ({ a: element, b: index }));
      
      console.log(data);

      或者显式返回:

      const my_arr = [1, 2, 4, 3, 4];
      const data = my_arr.map((element, index) => { return { a: element, b: index }; });
      
      console.log(data);

      【讨论】:

        【解决方案4】:

        我猜是一样的

        var my_arr = [...Array(5).keys()]
        
        var result = my_arr.map((element,index) => ({ a: element, b: element + 1 }));
        
        console.log('result', result)

        【讨论】:

          【解决方案5】:

          原来如此

          查看输出:

          var results = [];
          [...Array(11).keys()].forEach((el) => {
            if (el % 2 === 0) {
              results.push({ a: el, b: el + 1 })
            }
          })
          
          console.log('results',results)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-05-30
            • 2021-02-17
            • 2023-03-14
            • 2017-03-13
            • 1970-01-01
            • 1970-01-01
            • 2021-09-10
            相关资源
            最近更新 更多