129

Possible Duplicate:
Accessing properties of an array of objects

Given:

[{
    'id':1,
    'name':'john'
},{
    'id':2,
    'name':'jane'
}........,{
    'id':2000,
    'name':'zack'
}]

What's the best way to get:

['john', 'jane', ...... 'zack']

Must I loop through and push item.name to another array, or is there a simple function to do it?

peter-b
  • 4,073
  • 6
  • 31
  • 43
PK.
  • 2,471
  • 3
  • 24
  • 30
  • Are you sure you need to convert it to an array like that? Oftentimes, doing a conversion like this is an indication that you may be going about your underlying problem the wrong way. It might be useful to take a step back and make sure that's not the case here. – Shauna Dec 20 '12 at 13:25
  • @shauna my problem is this. im using bootstrap's typeahead it only access the second format: which is a array of string. my ajax calls will return the first format cuz i need the ID. i can of cuz go and extend boostrap's typeahead but rather do this: send the 2nd format to bootstrap. just keep the first format around and when user selects a choice check this first object and use the id as needed. – PK. Dec 20 '12 at 13:36

4 Answers4

211

If your array of objects is items, you can do:

var items = [{
  id: 1,
  name: 'john'
}, {
  id: 2,
  name: 'jane'
}, {
  id: 2000,
  name: 'zack'
}];

var names = items.map(function(item) {
  return item['name'];
});

console.log(names);
console.log(items);

Documentation: map()

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
techfoobar
  • 65,616
  • 14
  • 114
  • 135
11

Use the map() function native on JavaScript arrays:

var yourArray = [ {
    'id':1,
    'name':'john'
},{
    'id':2,
    'name':'jane'
}........,{
    'id':2000,
    'name':'zack'
}];

var newArray = yourArray.map( function( el ){ 
                                return el.name; 
                               });
Sirko
  • 72,589
  • 19
  • 149
  • 183
  • How can we map JSON structure like this ? `var yourArray = [ { "options": [ { 'id':2, 'name':'Javascript' },{ 'id':2000, 'name':'Ruby' } ] }];` – H.Husain Feb 09 '19 at 13:32
3

You can do this to only monitor own properties of the object:

var arr = [];

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        arr.push(p[key]);
    }
}
looper
  • 1,929
  • 23
  • 42
0

You can use this function:

function createStringArray(arr, prop) {
   var result = [];
   for (var i = 0; i < arr.length; i += 1) {
      result.push(arr[i][prop]);
   }
   return result;
}

Just pass the array of objects and the property you need. The script above will work even in old EcmaScript implementations.

Minko Gechev
  • 25,304
  • 9
  • 61
  • 68