0

I have an array from which I want to get only names.

var peoples = [
 { "name": "dod", "class": "a", "age": 12 },
 { "name": "john", "class": "b", "age": 14 },
 { "name": "henry", "class": "c", "age": 23 }
];

How can I get the name from each object with comma separation?

Gerald Schneider
17.8k10 gold badges64 silver badges79 bronze badges
asked Oct 10, 2013 at 6:28
2
  • 1
    peoples.map( function(v){ return v.name; }).join() Commented Oct 10, 2013 at 6:31
  • peoples[0].name Use a for-loop to iterate them all. Commented Oct 10, 2013 at 6:31

3 Answers 3

1

In jquery,

var peoples = [
 { "name": "dod", "class": "a", "age": 12 },
 { "name": "john", "class": "b", "age": 14 },
 { "name": "henry", "class": "c", "age": 23 }
];
var names = new Array();
$.each(peoples,function(key,value){
 names[key] = value.name;
});
namelist = names.join(",");
console.log(namelist);

http://jsfiddle.net/9344Q/

answered Oct 10, 2013 at 6:34
Sign up to request clarification or add additional context in comments.

3 Comments

few comments var names = new Array(); => var names = [] and names.join(",") => names.join() as default join charactor is ,
I don't know, question not asked about jQuery solution and answer is jQuery based .. there good solution for this in native js .. instead of loading heavy JavaScript library
@rab In most cases, web sites will have jQuery, So it doesn't bother.
0

This will definitely do it in plain Javascript:

var peoples = [
 { "name": "dod", "class": "a", "age": 12 },
 { "name": "john", "class": "b", "age": 14 },
 { "name": "henry", "class": "c", "age": 23 }
];
var arr = [];
peoples.forEach(function(name) {
 arr.push(name['name']);
});
console.log(arr.join(','));
answered Oct 10, 2013 at 6:34

1 Comment

as Array.prototype.forEach is part of Ecmasript 5, it better to use Array.prototype.map for this .
0
var peoples = [
 { "name": "dod", "class": "a", "age": 12 },
 { "name": "john", "class": "b", "age": 14 },
 { "name": "henry", "class": "c", "age": 23 }
];
alert(peoples.map( function(v){ return v.name; }).join());
answered Oct 10, 2013 at 6:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.