-1

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' }
];

What I've tried:

arr.reduce((a, c) => ((a[c] = c), a), {});
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
Aleem S
  • 151
  • 1
  • 18

4 Answers4

7

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,
   }
})
cseitz
  • 1,116
  • 4
  • 16
1

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' } ]
syahiruddin
  • 401
  • 5
  • 14
1

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);
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
1

Another way using With Object.fromEntries, you can convert from Array to Object

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

const result = arr.map(item => Object.fromEntries([["name",item]]));

console.log(result);