Markcce Eros Markcce Eros - 1 month ago 6
Javascript Question

Create arrays from JavaScript objects

I have some data which looks like this:

{
"obj":
[
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}


What I need to do is to create 2 arrays from it.

For example:

namelist[];
agelist[];


so the result would be:

namelist: ['name1', 'name2'];

agelist: [24, 17];


My question is, how can I do this?

Answer

You could use this ES6 code, and use the unitary plus for getting the ages as numbers. Assuming your object is stored in variable data:

var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );

var data = {
    "obj": [
        {
            "name": "name1",
            "age": "24"
        },
        {
            "name": "name2",
            "age": "17"
        }
    ]
};

var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );

console.log(namelist);
console.log(agelist);

Comments