MasterScrat MasterScrat - 1 month ago 11
Javascript Question

Replace an element of an object by one of its own sub-elements

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 = => {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?

Answer Source

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);