我有一個如下所示的陣列
const arr = [
{
id: "first",
val: 'ganguly',
},
{
id: "third",
val: 'sachin',
},
]
const selectedVaue ='dhoni';
如果 id 與“第三”匹配,則替換為特定鍵的值
const list = arr.filter(data => data.id === 'third');
if (list.length > 0 ) {
// code
}
預期結果如下:
const arr = [
{
id: "first",
val: 'ganguly',
},
{
id: "third",
val: 'dhoni',
},
]
uj5u.com熱心網友回復:
您可以使用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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464694.html
標籤:javascript 打字稿 筛选
上一篇:如何將陣列項添加到另一個陣列中
