teelou teelou - 4 months ago 22
Javascript Question

Javascript get all value of keys in array?

How can I get all values of keys in an array without jQuery?

var species = [{"code_name":"b","public_name":"a"},{"code_name":"d","public_name":"c"},{"code_name":"f","public_name":"e"}];

var speciesVals = Object.keys(species).map(function (val, key) {
return val;
});


Result:

[ '0',
'1',
'2',
'_atomics',
'_parent',
'_cast',
'_markModified',
'_registerAtomic',
'$__getAtomics',
'hasAtomics',
'_mapCast',
'push',
'nonAtomicPush',
'$pop',
'pop',
'$shift',
'shift',
'pull',
'splice',
'unshift',
'sort',
'addToSet',
'set',
'toObject',
'inspect',
'indexOf',
'remove',
'_path',
'isMongooseArray',
'validators',
'_schema' ]


But I am after:

["code_name":["b", "d", "d"], "public_name":["a", "c", "e"]


Is it possible?

EDIT:

What about this:

[{"code_name":["b", "d", "d"]}, {"public_name":["a", "c", "e"}]

Answer

Sure it's possible. If your object keys are the same for every object in the array, you can do:

var species = [{"code_name":"b","public_name":"a"},{"code_name":"d","public_name":"c"},{"code_name":"f","public_name":"e"}];
var res = {code_name: [], public_name: []};
   
for(var i = 0; i < species.length; i++){
    res.code_name.push(species[i].code_name);
    res.public_name.push(species[i].public_name);
}

console.log(res);


EDIT

To get an array of objects:

var species = [{"code_name":"b","public_name":"a"},{"code_name":"d","public_name":"c"},{"code_name":"f","public_name":"e"}];
var res = [{code_name: []}, {public_name: []}];
   
for(var i = 0; i < species.length; i++){
    res[0].code_name.push(species[i].code_name);
    res[1].public_name.push(species[i].public_name);
}

console.log(res);