如何更新特定数组元素的值?
let data = [
{title: 'food', category: 'food', value: 10},
{title: 'good', category: 'hood', value: 40},
{title: 'sood', category: 'lending', value: 20},
]
答案 0 :(得分:0)
您可以简单地执行以下操作:
data[1].value = "aValue"
要更新所有标题为“食品”的物品:
data.filter(e => e.title === "food").forEach(e => e.value = "aValue" )
要更新所有类别为“罩”的物品:
data.filter(e => i.category === "hood").forEach(e => e.value = "aValue" )
答案 1 :(得分:0)
您的问题太短了,无法理解,但是您可以尝试通过查找对象并使用此功能替换它来更新任何对象。
let data = [
{title: 'food', category: 'food', value: 10},
{title: 'good', category: 'hood', value: 40},
{title: 'sood', category: 'lending', value: 20},
];
/**
* By this function you can update any array of objects and return the * updated array.
*
* @param array data The data array to update.
* @param string findKey The key to select the object to update.
* @param string findValue The value which has to match for object selection.
* @param string replaceKey Which key to update.
* @param string replaceValue replaceKey updated by which value.
*
* @return array The updated array.
*/
function update(data, findKey, findValue, replaceKey, replaceValue) {
return data.map(value => {
if (value[findKey] === findValue) {
value[replaceKey] = replaceValue;
}
return value;
});
}
// Here I update the data array by finding the object which has the 'title' value is 'food' and replace the 'value' field by 50
const updatedData = update(data, 'title', 'food', 'value', 50);
console.log(updatedData);
答案 2 :(得分:0)
只需使用:
arr.map((obj) => {
if(obj.value === 'Old value'){
obj.value = 'New value';
}
return obj;
})