繁体   English   中英

如何在对象数组中仅 rest 的 object 的一个值

[英]How to rest only one value of an object inside an array of Objects

我有一个对象数组。 所有对象都具有以下键和值:

const arr=[ { name: 'beer', amount: 50, price: 50 }]


function changeValue(){

// here I would like to receive back an array with the same object keys and values except amount.
// arr.amount should be 0
}

<button onclick='changeValue()'> Reset Amount </button>

我怎样才能用相同的对象取回相同的精确数组,除了每个对象的数量应该为 0? 我认为这可以通过扩展运算符来完成。

您可以使用 rest 参数。

 const arr=[ { name: 'beer', amount: 100, price: 50 }, { name: 'test', amount: 50, price: 10 }]; const res = arr.map(({amount, ...rest})=>({...rest, amount: 0})); console.log(res);

你需要 map 原阵列

function changeValue(something){
   return arr.map( it => ({
        ...it, 
        amount: something
   }))
}

您可能还想根据某些条件过滤it

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM