1

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"}]

1
  • 1
    Why not just use a loop? for( var result = {}, i=0, l=species.length, k; i<l; i++) { for( k in species[i]) if( species[i].hasOwnProperty(k)) { result[k] = result[k] || []; result[k].push(species[i][k]); }} Commented Jul 25, 2016 at 9:32

3 Answers 3

3

Use JavaScript Array#reduce method.

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

var temp = species.reduce(function(res, v) {
  // iterate over object(array element)
  Object.keys(v).forEach(function(k) {
    // define property as array if not defined
    res[k] = res[k] || [];
    // push the value to prefered array
    res[k].push(v[k]);
  });
  // return the updated object
  return res;
  // define the initial value as object to hold the result
}, {});

// now create your expected result
var speciesVals = Object.keys(temp) // get all property names
  .map(function(v) { //iterate over them to generate the result array
    var obj = {}; // create object for 
    obj[v] = temp[v]; // add property
    return obj; // return object (which is the new array element)
  });


console.log(speciesVals);

Sign up to request clarification or add additional context in comments.

2 Comments

thanks. what about this: [{"code_name":["b", "d", "d"]}, {"public_name":["a", "c", "e"}] ?
@teelou : glad to help you :)
1

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);

5 Comments

You're welcome! Yeah, no need to overcomplicate because this is a simple old-school iteration task. :)
i totally agree with u. was overthinking to .prototype side!
That makes sense if you plan to do many variations of this (like fetching different keys, using different original array structure, different organization of results, etc.), but if you want a code that solves this single task efficiently, I'd go with a single loop every time.
cool. thanks for the tip. Btw, how can I make this instead [{"code_name":["b", "d", "d"]}, {"public_name":["a", "c", "e"}] - objects in an array?
No problem, I'm glad I could help.
1

I suggest to use a fixed array for the properties, because you need only 'code_name and public_name.

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

species.forEach(function (a) {
    ['code_name', 'public_name'].forEach(function (k) {
        speciesVals[k] = speciesVals[k] || [];
        speciesVals[k].push(a[k]);
    });
});

console.log(speciesVals);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.