Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a javascript object array to a string array of the object attribute I want? [duplicate]

Tags:

javascript

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?

like image 348
PK. Avatar asked Dec 20 '12 13:12

PK.


People also ask

How do I convert a JavaScript object array to a string array of the object attribute I want?

Stringify a JavaScript ArrayUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(arr);

How do I convert an array of objects to a string array?

As list. toArray() returns an Object[], it can be converted to String array by passing the String[] as parameter.


2 Answers

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

like image 99
techfoobar Avatar answered Oct 01 '22 20:10

techfoobar


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;                                 }); 
like image 23
Sirko Avatar answered Oct 01 '22 19:10

Sirko