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:
{}
: The initialValue should be theArray
instead.(a[c] = c
: You want to define the specificname
instead of eachc
value
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?"