简体   繁体   中英

How to get index of a named object inside an array

I have an array that contains multiple named objects. I already tried to use the javascript filter method and indexOf() but it returns -1.

Tried indexOf like so:

let idx = manifest.coffee.beans.indexOf("CB_2020_0005")

This is my manifest object

manifest: {
    userData: {},
    coffee: {
        beans: [
            "CB_2020_0001": {
                price: 2.5,
                amount: 5
            },
            "CB_2020_0005": {
                price: 3.3,
                amount: 10
            }
        ],
        instant: []
    }
}

How should I retrieve the index number of for example the second object "CB_2020_0005" inside of manifest.coffee.beans?

You can use 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM