James Reid
James Reid

Reputation: 459

How to convert dictionary to a string angularjs

I am currently working on my project using angularjs. I got everything already it is just that, i need to convert the dictionary list to a string separated by comma. I can only do this using python.

[{"name":"john"},{"name":"mark"},{"name":"peter"}]

I want to convert them to string

"john,mark,peter"

I would really appreciate your help. :)

Upvotes: 0

Views: 816

Answers (4)

Abdullah Al Noman
Abdullah Al Noman

Reputation: 2878

The map() method creates a new array with the results of calling a function for every array element. Use this to loop and then add that value to a variable.

var dict=[{"name":"john"},{"name":"mark"},{"name":"peter"}];
var string;
dict.map(function(value){
   //do any stuff here
  string+=value["name"]+",";
});
console.log(string);

Upvotes: 1

Akash KC
Akash KC

Reputation: 16310

You can simply iterate over each key-value pair and concat the extracted value with comma.

var obj =  [{"name":"john"},{"name":"mark"},{"name":"peter"}]
var result = '';
for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            result += obj[p].name + ",";
        }
 }

result = result.replace(/,$/g,''); // to trim trailing comma

Upvotes: 0

Icycool
Icycool

Reputation: 7179

.map and then .join will do

var array = [{"name":"john"},{"name":"mark"},{"name":"peter"}];
var names = array.map(function(item) {
   return item.name;
}).join(',');

Upvotes: 1

TheVillageIdiot
TheVillageIdiot

Reputation: 40527

Try map function to concatenate the values:

var dict=[{"name":"john"},{"name":"mark"},{"name":"peter"}];

var str="";
dict.map(function(a){
  str+=a["name"]+",";
});

//feels ironical as question has AngularJS tag
document.getElementById("log").innerText=str;
<div id="log"></div>

Upvotes: 0

Related Questions