1

I have an array containing objects that looks like this:

var persArr = [
 {name: "Adam", age: 37}, 
 {name: "Ben", age: 36}, 
 {name: "Chris", age: 46}
 ];

What I would like to do is create a string variable which takes the given names in each object in the array and puts them together like this:

var str = "Adam, Ben, Chris";

Any suggestions as to achieve this?

Prabhuram
1,2689 silver badges15 bronze badges
asked Nov 19, 2013 at 9:12

3 Answers 3

3

You can use map and join:

var str = persArr.map(function (pers) {
 return pers.name;
}).join(", ");
answered Nov 19, 2013 at 9:14
Sign up to request clarification or add additional context in comments.

Comments

1

Try with:

var names = [];
for (var k in persArr) {
 names.push(persArr[k].name);
}
var str = names.join(', ');
answered Nov 19, 2013 at 9:14

Comments

0

try something like this

 var persArr = [{name: "Adam", age: 37}, {name: "Ben", age: 36}, {name: "Chris", age: 46}];
 var ar_length = persArr.length;
 var temp_arr = [];
 for(var i= 0;i<ar_length;i++){
 temp_arr.push(persArr[i].name);
 }
 alert(temp_arr.join(','));
answered Nov 19, 2013 at 9:17

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.