简体   繁体   中英

How to get an array inside an array?

Hi I have trouble with an array response of json. I'm supposed to get the members of the objects. but that array is inside another array.
This is the array that is being returned.

var arr = [
[
    {
        "id": 4243430853,
        "email": "jayduco2@gmail.com",
    },
    {
        "id": 4227666181,
        "email": "deofederickduran@gmail.com",

    },
    {
        "id": 4227644293,
        "email": "kfsucayan@gmail.com",

    }
],
[
    {
        "id": 4243430854,
        "email": "jayduco2@gmail.com",
    },
    {
        "id": 4227666182,
        "email": "deofederickduran@gmail.com",

    },
    {
        "id": 4227644294,
        "email": "kfsucayan@gmail.com",

    }
]   
];

How can i dig down to the values? before I would use arr[i].email , but now it doesn't work. I've tried arr[0].[i].email, but returns be the error missing name after . operator missing name after . operator . Is there a way that I can remove that outer array?

It should be arr[i][j].email . i to loop over the array arr itself and j to loop over each sub-array.

arr[i] will give you something like this (if i == 0 for example):

[
    {
        "id": 4243430853,
        "email": "jayduco2@gmail.com",
    },
    {
        "id": 4227666181,
        "email": "deofederickduran@gmail.com",
    },
    {
        "id": 4227644293,
        "email": "kfsucayan@gmail.com",
    }
]

and then arr[i][j] will give something like this (if i == 0 and j == 2 ):

{
    "id": 4227644293,
    "email": "kfsucayan@gmail.com",
}

then you can access the email property using arr[i][j].email .

There's two ways to access objects in Javascript: using periods or using square brackets. Here, you're trying to mix the two, which works, but probably isn't the best practice. You should pick whichever is best for the situation. Here, you'd want to use the brackets:

arr[i][j]["email"];

Note that when using variables, you will always need to use brackets as opposed to periods.

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