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()...
jo_va
  • 13,504
  • 3
  • 23
  • 47
M4V3N
  • 600
  • 6
  • 21

5 Answers5

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);
jo_va
  • 13,504
  • 3
  • 23
  • 47
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)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0
arr.map(p => 
 {   
   return {value: p}; 
 })
Potato
  • 770
  • 1
  • 8
  • 18
  • 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. – undetected Selenium Apr 04 '19 at 09:30
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);
nircraft
  • 8,242
  • 5
  • 30
  • 46
Heju
  • 123
  • 1
  • 1
  • 6
  • Please describe what did you change and why, to help others identify the problem and understand this answer! – FZs Apr 04 '19 at 18:28
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 })));
Azeem Aslam
  • 554
  • 5
  • 19