arrays - How to get values by key in Javascript - Stack Overflow

Is there any nifty way to get values from an array of hashes:var foo = {a: "aFirst", b: "

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
Add a ment  | 

3 Answers 3

Reset to default 4

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

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

相关推荐

  • arrays - How to get values by key in Javascript - Stack Overflow

    Is there any nifty way to get values from an array of hashes:var foo = {a: "aFirst", b: "

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信