簡體   English   中英

從 object 數組中查找和更改特定項目

[英]Find and Change specific item from an object array

我正在處理一個像

arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}] 現在我想給數組提供條件,就像我在數組中得到 id 'fifth' 一樣,數組將變為

arr = [{id:'first',name:'John'},{id:'sixth',name:'Kat'},{id:'eitghth',name:'Isa'}]

就像只修改了項目的一部分。 我怎么能在js中做到這一點?

您可以使用Array.prototype.find來定位條目,然后簡單地更新其id屬性:

 const arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}]; const entry = arr.find(item => item.id === 'fifth'); entry.id = 'sixth'; console.log(arr);

您還可以使用Array.prototype.findIndex來檢索要替換的條目的索引,並相應地對其進行修改:

 const arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}]; const targetIndex = arr.findIndex(item => item.id === 'fifth'); arr[targetIndex].id = 'sixth'; console.log(arr);


但是,上面的兩種方法只能幫助找到第一個匹配元素 如果數組中有多個 ID 為fifth的條目,那么最好使用迭代:

 const arr = [{id:'fifth',name:'Kat'},{id:'fifth',name:'Kat'},{id:'fifth',name:'Kat'}]; arr.forEach(item => { if (item.id === 'fifth') { item.id = 'sixth'; } }); console.log(arr);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM