1

Wonder if there is a cleaner way of doing this then just iterating over every single object, and incrementally rebuilding the array (in Javascript).

var myArray = [{id:10,name:'bob'},{id:30,name:'mike'},{id:40,name:'jay'},{id:50,name:'chris'},{id:60,name:'snake'}];

Indented array output --> [10,30,40,50,60]

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
vicsz
  • 9,552
  • 16
  • 69
  • 101
  • 2
    Yes, see here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map – elclanrs Sep 15 '14 at 20:56

1 Answers1

2

map is an higher-order function that applies a function to every member of an array, returning the resulting array.

var myArray = [{
    id: 10,
    name: 'bob'
}, {
    id: 30,
    name: 'mike'
}, {
    id: 40,
    name: 'jay'
}, {
    id: 50,
    name: 'chris'
}, {
    id: 60,
    name: 'snake'
}];

myArray.map(function (obj) {
    return obj.id;
}); // [10, 30, 40, 50, 60]

Note that this method is absent from IE before version 9, but you can use a polyfill instead if you need to support those browsers.

If you already reference jQuery, $.map offers the same functionality. I suppose underscore.js and the likes also offer an alternative.

dee-see
  • 23,668
  • 5
  • 58
  • 91