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?

3 Answers 3

3

You can use map and join:

var str = persArr.map(function (pers) {
    return pers.name;
}).join(", ");
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(', ');

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

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.