Skip to content Skip to sidebar Skip to footer

How To Convert An Array To Array Of Objects With Same Keys In Javascript?

Consider a simple array that contains a set of values. var arr = ['ab', 'cd', 'ef']; I'd like to convert the above array into, [ { name: 'ab' }, { name: 'cd' }, { name: 'ef'

Solution 1:

You can do this using Array.map, which allows you to specify a function that returns a new item to replace in the array.

arr.map(o => ({ name: o }))

Here's one without fancy arrow function shorthand, just in case you are confused.

arr.map(function(o) {
   return {
      name: o,
   }
})

Solution 2:

You've tried: arr.reduce((a, c) => ((a[c] = c), a), {});

Your code there are 2 problems:

  1. {}: The initialValue should be the Array instead.
  2. (a[c] = c: You want to define the specific name instead of each c value

The .reduce syntax

arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])

The finish solution .reduce should be like this:

const arr = ['ab', 'cd', 'ef'];

const result = arr.reduce((acc, currItem) => {
  acc.push({name: currItem});
  return acc;
}, []);
console.log(result);

Or just .map() like this.

const arr = ['ab', 'cd', 'ef'];

const result = arr.map(item => ({name: item}));
console.log(result);

Solution 3:

You can use forEach() and create a new array of objects pushing each new object.

var arr = ['ab', 'cd', 'ef'];

const newObjArr = [];

arr.forEach((str) => newObjArr.push({ name: str }))

console.log(newObjArr); //[ { name: 'ab' }, { name: 'cd' }, { name: 'ef' } ]

Post a Comment for "How To Convert An Array To Array Of Objects With Same Keys In Javascript?"