我想知道找到位于陣列內的專案的索引的最佳方法是什么,并且該陣列位于另一個陣列內。
這是我擁有的資料型別:
const list = [
{
id: 1,
items: [
{
name: "milk",
id: 99
},
{ name: "water", id: 33 }
]
},
{
id: 4,
items: [
{
name: "oranges",
id: 22
},
{ name: "patatoes", id: 13 }
]
}
];
假設我想知道名為“milk”的專案的索引,我已經知道父物件的 id (1),并且我也知道專案的 id(99)。
我的目標是將專案的名稱從“牛奶”更改為“奶酪”,我的第一個想法是這樣做:
const firstObjectIndex = arr.findIndex(el => el.id === 1)
if(firstObjectIndex !== -1){
const itemIndex = arr[firstObjectIndex].items.findIndex(item => item.id === 99)
if(itemIndex !== -1){
// this is where I change the name to cheese
arr[firstObjectIndex].items[itemIndex].name = 'Cheese'
}
}
我上面使用的方法可以完成這項作業,但我想知道在 JavaScript 中是否有更好的方法來做到這一點?任何幫助將不勝感激
uj5u.com熱心網友回復:
您實際上并不需要索引,而是物件本身。因此,使用Array#find. 這允許使用可選的鏈接運算子輕松地將兩個搜索組合到一個陳述句中。
const list=[{id:1,items:[{name:"milk",id:99},{name:"water",id:33}]},{id:4,items:[{name:"oranges",id:22},{name:"patatoes",id:13}]}];
let obj = list.find(x => x.id === 1)?.items.find(y => y.name === 'milk');
if(obj) obj.name = 'Cheese';
console.log(list);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492522.html
標籤:javascript
