简体   繁体   中英

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.

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.

arr.reduce(callback[, initialValue])

The reduce() callback method takes accumulator and currentValue parameters.

  • accumulator: Value is remembered throughout each iteration of the method and ultimately becomes the final returned value.
  • currentValue: The current element being processed in the array .

The {} is supplied as the last argument to reduce() as the initial value to start with. And with each iteration of the Array , we add to it ultimately creating the final Object .

Example: (ES6)

 const letters = ['a', 'b', 'c']; const obj = letters.reduce((accumulator, currentValue) => { accumulator[currentValue] = currentValue; return accumulator; }, {}); console.log(obj);

Example: (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.

You could map objects and join to a single object with 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.

 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.

 const a = ['a', 'b', 'c']; const o = a.reduce((s, a) => { s[a] = a; return s; }, {}); console.log(o);

Use reduce

 var arr = ['a', 'b', 'c']; var obj = arr.reduce(function(obj, value) { obj[value] = value; return obj }, {}); console.log(obj)

The object.assign() might solve your problem.

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} console.log(objectValues)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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