简体   繁体   English

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

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

I'm wondering how I can transform an each item in an array into a specified object. 我想知道如何将数组中的每个项目转换为指定的对象。 You can see the code below for the array I start out with and the result I'm trying to achieve. 您可以看到我开始使用的数组的代码以及我想要实现的结果。 I'm trying to use the map function to no avail, and not sure if the array.map() function is the right function to use, or if maybe there is something in lodash that I could use. 我正在尝试使用map函数无效,并且不确定array.map()函数是否是正确使用的函数,或者如果lodash中可能存在我可以使用的东西。 Thanks! 谢谢!

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

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

You can use Array#reduce() 你可以使用Array#reduce()

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

You could map the new objects with the wanted key and assign to a single object. 您可以使用所需的键映射新对象并​​分配给单个对象。

 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: lodash 1:

you can use _.zipObject() with Array.map() : 你可以使用_.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: Lodash 2:

You can use Array.reduce() with _.set() : 您可以将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