0

So I have an array myarr[] of JSON objects in the form: { "a":"", "b":"" }

Are there efficient methods for getting an array of b:

[ myarr[0].b, myarr[1].b, myarr[2].b, ... ]

Or do I have to manually iterate through the myarr to build the array of b?

4
  • You will have to iterate the array, yes, but there are helper functions that can simplify the usage. Commented May 13, 2013 at 18:54
  • @Bergi What would those helpers be? Commented Feb 27, 2014 at 18:19
  • @dlackey: pluck for example as suggested (and re-implemented) in the answers. Commented Feb 27, 2014 at 18:21
  • @Bergi - Ah, thanks. I hand't heard of "pluck" and thought it was the name of am abstract value like people use "foo" and "bar". Commented Feb 27, 2014 at 18:26

4 Answers 4

2

Check out the underscore.js library.

I'd suggest checking out the implementation for pluck.

What you'd want to do is effectively: _.pluck(myarr, 'b')

Sign up to request clarification or add additional context in comments.

Comments

1

Why not have fun with prototypes and extend Array to obtain a handy and reusable function:

Array.prototype.pluck = function(key) {
    var i = this.length, 
        plucked = [];
    while(i --) {
        plucked[i] = this[i][key] || ""
    }

    return plucked;
}

With this one, you can do:

collection.pluck(keyName)

To get back your desired result. Check here for a working demo: http://jsfiddle.net/jYrNN/1/

1 Comment

Why the || ""? Just let the result be undefined.
1
var b_arr = $.map(myarr, function(val, i) { return val.b; });

FIDDLE

or wihtout jQuery

var b_arr = myarr.map(function(val) { return val.b })
                 .filter(function(n){return n || false});

1 Comment

OP doesn't use jQuery, so the native method might be more appropriate
-1

jQuery does provide api to parse json

$.each(myarr, function(key,value)
  {
    alert(key);
    alert(value);
  });

1 Comment

Neither does he need to parse JSON, nor do you use that method.

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.