[英]JavaScript, how to create an object out of an array?
I would like to convert an array that looks like this:我想转换一个看起来像这样的数组:
['foo', 'bar', 'baz']
to an object that looks like this:到一个看起来像这样的对象:
{
foo: true,
bar: true,
baz: true,
}
In most languages you would have some form of fill(keys, value)
function:在大多数语言中,你会有某种形式的fill(keys, value)
函数:
var array = ['foo', 'bar', 'baz'];
var object = fill(array, true);
// object = { foo: true, bar: true, baz: true}
But in JS I can only find one for numeric keys using a range, not a list of keys.但是在 JS 中,我只能找到一个使用范围的数字键,而不是键列表。 Is there a fill function that will do exactly that?是否有一个填充功能可以做到这一点?
Try this:尝试这个:
const data = ['foo', 'bar', 'baz']
const asObject = Object.fromEntries(data.map(d => ([d, true])))
console.log(asObject)
You can build an object with .reduce()
:您可以使用.reduce()
构建对象:
var object = array.reduce((o, e) => (o[e] = true, o), {});
edit — or the clever Object.fromEntries()
solution mentioned in a comment.编辑——或者评论中提到的聪明的Object.fromEntries()
解决方案。
There isn't such function as fill(keys, value)
that you mentioned, but you could also do so:没有您提到的fill(keys, value)
之类的功能,但您也可以这样做:
let tab = ['foo', 'bar', 'baz']; let obj = {} tab.forEach(v=>{obj[v]=true}); console.log(obj)
You can map the array values to entries (key, value pairs) and then transform the matrix into an object.您可以将数组值映射到条目(键、值对),然后将矩阵转换为对象。
const arr = ['foo', 'bar', 'baz'], obj = Object.fromEntries(arr.map(v => [v, true])); console.log(obj);
You can create a new object, loop over the array and add each value to it.您可以创建一个新对象,遍历数组并将每个值添加到其中。
let arr = ['foo','bar','baz'];
let obj={};
arr.forEach(el => {obj[el] = true})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.