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?

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/

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(','));

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

Comments

Your Answer

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.