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
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
Share
Improve this question
asked Jun 1, 2013 at 8:19
Jackie ChanJackie Chan
2,6626 gold badges36 silver badges71 bronze badges
1
-
1
sorry but this line isn't clear to me (
myArrOfHashes.map(b) // => bFirst, aSecond, aThird
) can you elaborate more plz. – yogi Commented Jun 1, 2013 at 8:24
3 Answers
Reset to default 4One 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.)
Well, not quite like that, but you could try this:
myArrOfHashes.map(function(hash){ return hash.b; });
It's not 100% clear what you want, but try
var map = function(key) {
return function(value) {
return value[key];
};
};
console.log(myArrOfHashes.map(map('b')));
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742354186a4428111.html
评论列表(0条)