0

I would like to convert the following array to an array of objects:

let arr = ['tree', 'apple', 'orange']

to

arr = [
  {value: tree},
  {value: apple},
  {value: orange}
]

My solution so far is:

let temp = []; 
arr.forEach(x => {   
   temp.push({value: p}); 
});

arr = temp

how do I solve this problem with the array.map() functionality so I can just call

arr.map()...
2
  • 3
    arr.map(value => ({value})) Commented Apr 4, 2019 at 9:11
  • 5
    arr.map(o => ({value: o}))? Commented Apr 4, 2019 at 9:12

5 Answers 5

4

You can do it like this with Array.prototype.map():

const arr = ['tree', 'apple', 'orange'];

const result = arr.map(value => ({ value }));

console.log(result);

Or more explicitly, with no implicit return or object shorthand notation:

const arr = ['tree', 'apple', 'orange'];

const result = arr.map(x => {
  return { value: x };
});

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

2

What you return from the .map callback will be the new item in the array at that index - so, just replace your temp.push( with return:

let arr = ['tree', 'apple', 'orange'];
arr = arr.map(x => {
  return { value: x };
});
console.log(arr);

Or, to implicitly return from the arrow function for more conciseness:

let arr = ['tree', 'apple', 'orange'];
arr = arr.map(x => ({ value: x }));
console.log(arr);

(for code clarity, you might consider not overwriting arr though - assign to a new variable name instead, if you can, that way arr can be a const)

2 Comments

isn't there a way to directly manipulate the array without assignment?
You could reassign each index: arr[i] = ({ value: arr[i] }), but both reassignment and mutation are better avoided when not necessary
0
arr.map(p => 
 {   
   return {value: p}; 
 })

1 Comment

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
0

Map is pure it will not change your target or parent array. Map creates it's own copy of array and returns results by doing operations on copied array.

let arr = ['tree', 'apple', 'orange'];
 
console.log(arr.map(x => ({ value: x })));

Comments

0

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

You can use this on arr to get the updated array:

let arr = ['tree', 'apple', 'orange'];
let arrOfObjects = arr.map( el => { return { value: el } })

console.log(arrOfObjects);

1 Comment

Please describe what did you change and why, to help others identify the problem and understand this answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.