2

Let's say I have:

let list = [{a: {b: 'foo'}}, {a: {b: 'bar'}}]

I want to end up with:

list = [{a: 'foo'}, {a: 'bar'}]

This works:

list = list.map(d => {d.a = d.a.b; return d})

But I have a bad feeling that changing the value in place is a bad idea.

Is there a cleaner way? is my solution actually valid?

MasterScrat
  • 7,090
  • 14
  • 48
  • 80

2 Answers2

1

It is not changing the value in place.

map method only creates a new array by applying a callback provided function for every item in the array.

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

For changing the value in place you can use forEach method.

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
1

You could use Array#forEach and change the object in situ, because you need not to return a new array, while you already mutate the original object of the array.

let list = [{ a: { b: 'foo' } }, { a: { b: 'bar' } }];

list.forEach(d => d.a = d.a.b);

console.log(list);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392