[英]How to convert an array to an object in Javascript without using loops?
I want to convert the following array:我想转换以下数组:
['a', 'b', 'c']
to the following object:到以下对象:
{a: 'a', b: 'b', c: 'c'}
How do I do it without using loop, ofcourse?我如何在不使用循环的情况下做到这一点,当然?
You'll want to use the Array.reduce()
method.您需要使用
Array.reduce()
方法。
The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.
reduce() 方法对数组的每个成员执行一个 reducer 函数(您提供的),从而产生一个输出值。
arr.reduce(callback[, initialValue])
The reduce()
callback method takes accumulator
and currentValue
parameters. reduce()
回调方法采用accumulator
和currentValue
参数。
array
. array
正在处理的当前元素。 The {}
is supplied as the last argument to reduce()
as the initial value to start with. {}
作为reduce()
的最后一个参数作为初始值提供。 And with each iteration of the Array
, we add to it ultimately creating the final Object
.并且随着
Array
每次迭代,我们添加到它最终创建最终的Object
。
Example: (ES6)示例: (ES6)
const letters = ['a', 'b', 'c']; const obj = letters.reduce((accumulator, currentValue) => { accumulator[currentValue] = currentValue; return accumulator; }, {}); console.log(obj);
Example: (ES5)示例: (ES5)
var letters = ['a', 'b', 'c']; var obj = letters.reduce(function (accumulator, currentValue) { accumulator[currentValue] = currentValue; return accumulator; }, {}); console.log(obj);
Reference: Array.prototype.reduce() mozilla documentation.参考: Array.prototype.reduce() mozilla 文档。
You could map objects and join to a single object with Object.assign
.您可以使用
Object.assign
映射对象并连接到单个对象。
var array = ['a', 'b', 'c'], object = Object.assign(...array.map(v => ({ [v]: v }))); console.log(object);
An alternative solution, you can also use the newer Object.fromEntries with map as well.另一种解决方案是,您也可以将较新的Object.fromEntries与 map 一起使用。
let arr = ['a', 'b', 'c']; let obj = Object.fromEntries(arr.map(m => [m,m])); console.log(obj);
You may use Array#reduce
to get the desired result.您可以使用
Array#reduce
来获得所需的结果。
const a = ['a', 'b', 'c']; const o = a.reduce((s, a) => { s[a] = a; return s; }, {}); console.log(o);
The object.assign()
might solve your problem. object.assign()
可能会解决您的问题。
Here is an example.这是一个例子。
var array = ['a', 'b', 'c'];
Object.assign( {}, array);
// {0: "a", 1: "b", 2: "c"}
The new object will have same index with the array.新对象将与数组具有相同的索引。
If you want the values of the array to be same with the key.如果您希望数组的值与键相同。
function arrayToObject( array)
{
var object = array.reduce( (obj, value) => {
obj[value] = value;
return obj
}, {});
return object;
}
arrayToObject( ['a', 'b', 'c'])
这可能是最短的版本:
console.log( ['a', 'b', 'c'].reduce((o, v) => (o[v] = v, o), {}) )
const values = ['a', 'b', 'c'] const objectValues = {...values} => const values = ['a', 'b', 'c'] const objectValues = {...values} =>
const values = ['a', 'b', 'c'] const objectValues = {...values} console.log(objectValues)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.