138

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?

2
  • 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. Commented Dec 20, 2012 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. Commented Dec 20, 2012 at 13:36

4 Answers 4

231

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()

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

7 Comments

@bru.scopelliti map() is native JavaScript and not just jQuery.
@bru.scopelliti - my answer has nothing to do with jQuery..
that's not jQuery. That's just modern javascript. Cool, huh?
@bru.scopelliti: I don't see any jQuery there.
You can use more modern syntax like this: names = items.map((item) => item.name);
|
12

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; 
                               });

1 Comment

How can we map JSON structure like this ? var yourArray = [ { "options": [ { 'id':2, 'name':'Javascript' },{ 'id':2000, 'name':'Ruby' } ] }];
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]);
    }
}

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.