简体   繁体   中英

Extract property values from nested array of objects and arrays

I have the following nested array of objects:

[
    {
        "info": [
            {
                "period": {
                    "start": "2020-01-01",
                    "end": "2020-01-31"
                },
                "info": [
                    {
                        "id": 036,
                        "name": "john",
                    },
                    {
                        "id": 037,
                        "name": "inna",
                    }
                ]
            }
        ]
    },
    {
        "info": [
            {
                "period": {
                    "start": "2020-01-01",
                    "end": "2020-01-31"
                },
                "info": [
                    {
                        "id": 045,
                        "name": "carl",
                    },
                    {
                        "id": 056,
                        "name": "tina",
                    }
                ]
            }
        ]
    }]

I want to extract all the values of the "name" property and put them in an array.

Output: ["john", "inna", "carl", "tina"] .

Try with this code:

const userNames = [];

data.map(item => {
    return item.info.map(registry => {
        return registry.info.map(user => userNames.push(user.name));
    })
})

Output: ["john", "inna", "carl", "tina"]

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