用它自己的子元素之一替换对象的元素
Replace an element of an object by one of its own sub-elements
假设我有:
let list = [{a: {b: 'foo'}}, {a: {b: 'bar'}}]
我想结束:
list = [{a: 'foo'}, {a: 'bar'}]
这个有效:
list = list.map(d => {d.a = d.a.b; return d})
但我有一种不好的预感,即就地更改值不是一个好主意。
有没有更简洁的方法?我的解决方案真的有效吗?
它没有改变原地的值。
map
方法仅通过为数组中的每个项目应用 callback
提供的函数来创建一个新数组。
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
要更改值,您可以使用 forEach
方法。
您可以使用 Array#forEach
并就地更改对象,因为您不需要 return 一个新数组,而您已经改变了数组的原始对象。
let list = [{ a: { b: 'foo' } }, { a: { b: 'bar' } }];
list.forEach(d => d.a = d.a.b);
console.log(list);
假设我有:
let list = [{a: {b: 'foo'}}, {a: {b: 'bar'}}]
我想结束:
list = [{a: 'foo'}, {a: 'bar'}]
这个有效:
list = list.map(d => {d.a = d.a.b; return d})
但我有一种不好的预感,即就地更改值不是一个好主意。
有没有更简洁的方法?我的解决方案真的有效吗?
它没有改变原地的值。
map
方法仅通过为数组中的每个项目应用 callback
提供的函数来创建一个新数组。
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
要更改值,您可以使用 forEach
方法。
您可以使用 Array#forEach
并就地更改对象,因为您不需要 return 一个新数组,而您已经改变了数组的原始对象。
let list = [{ a: { b: 'foo' } }, { a: { b: 'bar' } }];
list.forEach(d => d.a = d.a.b);
console.log(list);