如果条件为真,如何查找和替换值数组项
How to find and replace the value array item if condtion is true
我有一个如下所示的数组
const arr = [
{
id: "first",
val: 'ganguly',
},
{
id: "third",
val: 'sachin',
},
]
const selectedVaue ='dhoni';
如果 id 与 'third' 匹配,则将值替换为特定键
const list = arr.filter(data => data.id === 'third');
if (list.length > 0 ) {
// code
}
预期结果如下:
const arr = [
{
id: "first",
val: 'ganguly',
},
{
id: "third",
val: 'dhoni',
},
]
您可以使用 Array.prototype.map 并用 id
"third"
替换的值创建一个新数组。
const arr = [
{ id: "first", val: "ganguly" },
{ id: "third", val: "sachin" },
];
const selectedValue = "dhoni";
const res = arr.map((a) =>
a.id === "third" ? { ...a, val: selectedValue } : a
);
console.log(res);
或者你可以使用 Array.prototype.forEach 如果你想替换对象。
const arr = [
{ id: "first", val: "ganguly" },
{ id: "third", val: "sachin" },
];
const selectedValue = "dhoni";
arr.forEach((a, i) => {
if (a.id === "third") {
arr[i] = { ...a, val: selectedValue };
}
});
console.log(arr);
我有一个如下所示的数组
const arr = [
{
id: "first",
val: 'ganguly',
},
{
id: "third",
val: 'sachin',
},
]
const selectedVaue ='dhoni';
如果 id 与 'third' 匹配,则将值替换为特定键
const list = arr.filter(data => data.id === 'third');
if (list.length > 0 ) {
// code
}
预期结果如下:
const arr = [
{
id: "first",
val: 'ganguly',
},
{
id: "third",
val: 'dhoni',
},
]
您可以使用 Array.prototype.map 并用 id
"third"
替换的值创建一个新数组。
const arr = [
{ id: "first", val: "ganguly" },
{ id: "third", val: "sachin" },
];
const selectedValue = "dhoni";
const res = arr.map((a) =>
a.id === "third" ? { ...a, val: selectedValue } : a
);
console.log(res);
或者你可以使用 Array.prototype.forEach 如果你想替换对象。
const arr = [
{ id: "first", val: "ganguly" },
{ id: "third", val: "sachin" },
];
const selectedValue = "dhoni";
arr.forEach((a, i) => {
if (a.id === "third") {
arr[i] = { ...a, val: selectedValue };
}
});
console.log(arr);