JP.
JP.

Reputation: 5594

Condensing a Javascript array

I have a javascript array (from a yahoo pipe via JSONP) in which I have a sub-array called 'moby'.

I'd like to change the current structure:

value {
  callback => blah,
  generator => blah,
  items {
    0 {
      author => blah,
      category => blah,
      moby {
        day_no => 168,
        more => Keep_this_stuff
    },
    1 {
      author => blah,
      category => blah,
      moby {
        day_no => 167,
        more => Keep_this_stuff
    },... etc
  }
}

Into a more sparse object that looks something like this:

moby {
  168 {
    day_no => 168,
    more => Keep_this_stuff
  },
  167 {
    day_no => 167,
    more => Keep_this_stuff
  },... etc
}

I know how I'd do it in ruby (with the funky Array.collect) but I have no idea in Javascript! Any clues? (I have jQuery loaded in the page I'll be using this on)

Upvotes: 2

Views: 272

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

jQuery's map function could be used to transform an array of items into another array by using a translation function:

var result = $.map(value.items, function(element, index) {
    return element.moby;
});

Upvotes: 2

Related Questions