繁体   English   中英

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

[英]Transforming each item in an array into an object

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

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

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

你可以使用Array#reduce()

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

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

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

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

    console.log(transformedObject);

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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM