嗨,我正在尝试更新数组内的价格,我的目标是为所有ID发生都更新价格。
finalbrarray : [
{ id: 136, name: 'Chocolate - Chips Compound', price: '235.92' },
{ id: 137, name: 'Appetizer - Chicken Satay', price: '199.69' },
{ id: 138, name: 'Compound - Mocha', price: '431.16' },
{ id: 139, name: 'Syrup - Chocolate', price: '427.25' },
{ id: 139, name: 'Syrup - Chocolate', price: '427.25' },
{ id: 140, name: 'Lamb - Leg, Boneless', price: '183.44' },
{ id: 141, name: 'Jam - Blackberry, 20 Ml Jar', price: '493.03' },
{ id: 142, name: 'Lid - 3oz Med Rec', price: '259.42' }
]
我正在尝试使用以下功能更新价格:
const handleTextClick = id => e => {
const objIndex = finalbrArray.findIndex(br => br.id === id);
finalbrArray[objIndex].price = e.target.value;
const updatedObj = { ...finalbrArray[objIndex], price: e.target.value };
console.log(updatedObj);
console.table(finalbrArray);
};
这将更新首次出现的“ id:139”,即索引3。
我希望能够同时更改索引3和4的值。
您应该使用过滤器来获取匹配值的子集。findIndex
将返回数组中第一次出现的索引。
var finalbrarray = [{
id: 136,
name: 'Chocolate - Chips Compound',
price: '235.92'
},
{
id: 137,
name: 'Appetizer - Chicken Satay',
price: '199.69'
},
{
id: 138,
name: 'Compound - Mocha',
price: '431.16'
},
{
id: 139,
name: 'Syrup - Chocolate',
price: '427.25'
},
{
id: 139,
name: 'Syrup - Chocolate',
price: '427.25'
},
{
id: 140,
name: 'Lamb - Leg, Boneless',
price: '183.44'
},
{
id: 141,
name: 'Jam - Blackberry, 20 Ml Jar',
price: '493.03'
},
{
id: 142,
name: 'Lid - 3oz Med Rec',
price: '259.42'
}
]
// I'm passing id 139 for example. & setting the value to '500'
// filter returns an array where the criteria matches, then I'm calling forEach on new array returned by fiter and changing the values of price
finalbrarray.filter(br => br.id === 139).forEach((item) => {
item.price = '500'
})
// Open console to see the values updated
console.table(finalbrarray);
打开控制台以查看正在更新的值
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句