[英]Select only specific properties from an array of objects
假设我像这样创建对象:
updates.push({
id: this.ids[i],
point: point,
value: value
});
稍后我想在updates
对象上使用JSON.stringify
,但是我只需point
和value
例如:
updates[{point: 1, value: 12}, {point: 2, value: 24}]
什么是最好的 ES6 解决方案?
我查看了一些带有删除的示例,但这并不是我真正需要的,因为我不想删除 id。
如果updates
是一个数组。 那么你可能想要这样的东西:
const newArrayWithoutId = updates.map(({ point, value }) => {
return {
point,
value,
}
}
尝试以下操作:
JSON.stringify(updates.map(({point,value})=>({point,value})));
let updates = [{id : 1, point : 1, value: 2},{id : 1, point : 1, value: 2}]; console.log(JSON.stringify(updates.map(({point,value})=>({point,value}))));
Just ({id, ...rest}) => ({...rest})
对于答案来说太短了,那么这个怎么样?
const withoutId = ({id, ...rest}) => ({...rest}) const vals = [ {id: 'a', point: 1, value: 'foo'}, {id: 'b', point: 2, value: 'bar'}, {id: 'c', point: 3, value: 'baz', meaning: 42} ] const reduced = vals.map(withoutId) console.log(reduced)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.