Himmators
Himmators

Reputation: 15006

Can I get each value based on key from array of objects?

I have an array like this:

[
  {
    foo: bar,
    bar: foo,
  },
  {
    foo: bar,
    bar: baz,
  },
  {
    foo: bar,
    bar: foo,
  },
]

And I wish to get out an array that looks like this:

[foo, baz, foo]

Is this possible with pure JS or underscore? I only need to support modern browsers.

Upvotes: 0

Views: 69

Answers (4)

Paul
Paul

Reputation: 27423

UnderscoreJS has _.pluck()

_.pluck(yourArray,'bar') 
 => [foo,baz,foo]

From UnderscoreJS docs for _.pluck():

_.pluck(list, propertyName) 

A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.pluck(stooges, 'name');
 => ["moe", "larry", "curly"]

Upvotes: 2

Vishal
Vishal

Reputation: 166

Pure JS: This code will work in non strict mode. It's probably not the most efficient way. But, I think it's quite simple.

var A = [
  {
    foo: "bar",
    bar: "foo",
  },
  {
    foo: "bar",
    bar: "baz",
  },
  {
    foo: "bar",
    bar: "foo",
  },
]
var key = "bar";
var length = A.length;
var B = [];
for(var i = 0; i < length; ++i){
  if(A[i][key]){
    B[B.length] = A[i][key];
  }
}
console.log(B);

Upvotes: 1

Chris Bowdon
Chris Bowdon

Reputation: 31

With ES5 (pure JS):

var result = thatArray.map(function (x) { return x.bar; });

or with underscore:

var result = _.map(thatArray, function (x) { return x.bar; });

Upvotes: 3

Amit Joki
Amit Joki

Reputation: 59232

You could do it by Array.map

var result = arr.map(function(obj){
   return obj.bar;
});

Upvotes: 1

Related Questions