」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何根據特定屬性尋找並取代 JavaScript 陣列中的物件?

如何根據特定屬性尋找並取代 JavaScript 陣列中的物件?

發佈於2025-01-06
瀏覽:271

How to Find and Replace an Object in a JavaScript Array Based on a Specific Property?

在物件陣列中尋找具有特定屬性的物件

在Javascript 中,可以在未命名物件陣列中搜尋特定屬性基於屬性值匹配的物件。考慮以下數組:

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

找出物件:

要找出屬性「name」設定為「string 1」的對象,請使用 find() 方法。語法為:

let obj = arr.find(o => o.name === 'string 1');

此程式碼迭代陣列並傳回第一個對象,其中條件o.name === 'string 1' 為true。產生的obj 將包含以下資料:

{ name:"string 1", value:"this", other: "that" }

取代找到的物件:

找到物件後,可以將其替換為編輯後的版本。為此,請使用findIndex() 方法來取得陣列中物件的索引:

let index = array.findIndex(o => o.name === 'string 1');

然後,使用陣列的splice() 方法來取代該索引處的物件:

array.splice(index, 1, { new_name: "string 1", new_value: "updated" });

現在,陣列將包含更新的物件:

[
    { name:"string 1", value:"updated", other: "that" },
    { name:"string 2", value:"this", other: "that" }
]
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3