views:

100

answers:

1

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)

+2  A: 

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;
});
Darin Dimitrov
Good use of jQuery map, but this doesn't return exactly what he wants. Still, it's a good enough clue, so here's an upvote.
Mike Sherov
It's 90% there. Good answer.
Jonathan Julian
Good enough for me! Cheers!
JP