简体   繁体   中英

Javascript - How do I access an object in an array or change it to an array?

I get an object from api (list):

{
    "data": [
        {
            "id": 1,
            "name": "serverName",
            "advertisements": [
                {
                    "type_id": 1
                }
            ]
        }
    ]
}

Then I change it to an array by:

list.reduce((object, value) => ({ ...object, [value.id]: value }), {})

And I get an array. However, one item is still an object. What can be done to make an object in an array also be an array (without splitting it. It has to stay there)?

{ "id": 1, "name": "serverName", "advertisements": [ { "type_id": 1 } ] }

If you want to get the values you can do the following

let res = JSON.parse(request_response);
return res.data[0].id; // returns "1"

or if you want to get all the values

res.data.forEach(json => {
    return json.id; // you can access any property from here
});

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