Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values by key in Javascript

Is there any nifty way to get values from an array of hashes:

var foo = {a: "aFirst", b: "bFirst", c: "cFirst"};
var boo = {a: "aSecond", b: "bSecond", c: "cSecond"};
var bar = {a: "aThird", b: "bThird", c: "cThird"};
var myArrOfHashes = [foo, boo, bar];

So I would expect something like:

myArrOfHashes.map(b) // => bFirst, aSecond, aThird
like image 663
Jackie Chan Avatar asked Jan 29 '26 01:01

Jackie Chan


2 Answers

One easy way to do this - and many similar things - is with the Lo-Dash or Underscore libraries.

Here's an example from the Lo-Dash documentation:

var stooges = [
    { 'name': 'moe', 'age': 40 },
    { 'name': 'larry', 'age': 50 }
];

_.pluck(stooges, 'name');
// → ['moe', 'larry']

Even if you use a different approach for this particular problem, you should definitely check out these libraries. (They are very similar to each other; between the two I prefer Lo-Dash.)

like image 183
Michael Geary Avatar answered Jan 30 '26 14:01

Michael Geary


Well, not quite like that, but you could try this:

myArrOfHashes.map(function(hash){ return hash.b; });
like image 20
elclanrs Avatar answered Jan 30 '26 15:01

elclanrs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!