[英]How to get index of a named object inside an array
我有一個包含多個命名對象的數組。 我已經嘗試使用 javascript 過濾器方法和 indexOf() 但它返回 -1。
像這樣嘗試 indexOf :
let idx = manifest.coffee.beans.indexOf("CB_2020_0005")
這是我的清單對象
manifest: {
userData: {},
coffee: {
beans: [
"CB_2020_0001": {
price: 2.5,
amount: 5
},
"CB_2020_0005": {
price: 3.3,
amount: 10
}
],
instant: []
}
}
我應該如何檢索 manifest.coffee.beans 中的第二個對象“CB_2020_0005”的索引號?
您可以使用Array.prototype.findIndex() :
const obj = { manifest: { userData: {}, coffee: { beans: [ { "CB_2020_0001": { price: 2.5, amount: 5 } }, { "CB_2020_0005": { price: 3.3, amount: 10 } } ], instant: [] } } }; const idx = obj.manifest.coffee.beans.findIndex(o => "CB_2020_0005" in o); console.log(idx);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.