[英]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.