Skip to content
Advertisement

How to get a value in a JavaScript object by key

I have object and I would like to get the value of the id somehow by providing type = “EXTRA”. Could someone help with this?

{
    "packages": [
        {
            "id": "123",
            "type": "EXTRA",
            "name": "text",
            "extras": [
                {
                    "test": "1",
                    "test": "2"
                }
            ]
        },
        {
            "id": "234",
            "type": "BASE",
            "name": "text2",
            "extras": [],
        }
    ]
}

Advertisement

Answer

Your array

var arr = {
        "packages": [
            {
                "id": "123",
                "type": "EXTRA",
                "name": "text",
                "extras": [
                    {
                        "test": "1",
                        "test": "2"
                    }
                ]
            },
            {
                "id": "234",
                "type": "BASE",
                "name": "text2",
                "extras": [],
            }
        ]
    }

You can use the find() method for what you need providing the ‘EXTRA’ value of type

var result = arr.packages.find(x => x.type === 'EXTRA');

Your Output

console.log(result.id); //123

https://jsfiddle.net/kenpy/1moru9y4/9/

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement