将数组中的每个项目转换为一个对象

时间:2018-12-14 19:39:25

标签: javascript lodash

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

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

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

4 个答案:

答案 0 :(得分:4)

您可以使用Array#reduce()

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

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

console.log(res)

答案 1 :(得分:3)

您可以使用所需键映射新对象并​​分配给单个对象。

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

console.log(object);

答案 2 :(得分:2)

    const x = ["a", "b", "c"];    
    const transformedObject = x.reduce((acc, el) => {acc[el] = {"foo": "bar"}; return acc}, {})

    console.log(transformedObject);

答案 3 :(得分:0)

破折号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>