0

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.

1
  • 1
    So loop through the Array, read the object, push to an array. Commented Dec 9, 2014 at 14:34

4 Answers 4

3

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; });
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

You could do it by Array.map

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

Comments

1

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

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.