【问题标题】:Transforming each item in an array into an object将数组中的每一项转换为对象
【发布时间】:2018-12-14 19:39:25
【问题描述】:

我想知道如何将数组中的每个项目转换为指定的对象。您可以在下面看到我开始使用的数组的代码以及我想要达到的结果。我试图使用map 函数无济于事,并且不确定array.map() 函数是否是正确使用的函数,或者lodash 中是否有我可以使用的东西。谢谢!

const x = ["a", "b", "c"];

// expected result
{
  "a": {"foo": "bar"},
  "b": {"foo": "bar"},
  "c": {"foo": "bar"},
}

【问题讨论】:

  • 什么是{ foo: 'bar' }?它来自哪里?
  • 简单的forEach有什么问题:let res = {}; x.forEach(e => res[e] = {'foo': 'bar'});

标签: javascript lodash


【解决方案1】:

您可以使用Array#reduce()

const x = ["a", "b", "c"];

const res = x.reduce((a,c)=> (a[c] = {foo:'bar'},a) , {})

console.log(res)

【讨论】:

    【解决方案2】:

    您可以使用想要的键映射新对象并​​分配给单个对象。

    const
        x = ["a", "b", "c"],
        object = Object.assign(...x.map(k => ({ [k]: { foo: "bar" } })));
    
    console.log(object);

    【讨论】:

      【解决方案3】:
          const x = ["a", "b", "c"];    
          const transformedObject = x.reduce((acc, el) => {acc[el] = {"foo": "bar"}; return acc}, {})
      
          console.log(transformedObject);
      

      【讨论】:

        【解决方案4】:

        lodash 1:

        您可以将_.zipObject()Array.map() 一起使用:

        const data = ["a", "b", "c"];
        
        const result = _.zipObject(data, data.map(() => ({ for: 'bar' })));
         
        console.log(result)
        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

        Lodash 2:

        您可以将Array.reduce()_.set() 一起使用:

        const data = ["a", "b", "c"];
        
        const result = data.reduce((r, c) => _.set(r, `${c}.foo`, 'bar'), {});
         
        console.log(result)
        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-11-24
          • 2021-09-14
          • 2021-12-13
          • 2019-07-29
          • 2022-01-14
          • 1970-01-01
          相关资源
          最近更新 更多