Print object value separated by comma

I have to pass the following data obeject to a webservice

var data = {
id : 123,
code: "John","Ashley","Travis","Jack"
}

From this JSon response:


var obj = {
  "webservice_status" : {
    "status" : "SUCCESS",
    "message" : ""
  },
  "codes" : [ {
    "ID" : 22,
    "name" : "John"
  }, {
    "ID" : 22,
    "name" : "Ashley"
  }, {
    "ID" : 22,
    "name" : "Travis"
  }, {
    "ID" : 22,
    "name" : "Jack"
  } ]
}

I have aJSFiddle here. Is it possible to print each name in the data object separated by comma as shown above? Thanks

Got it working till this part :

But instead of printing all arraly items in one string , I want each one of them to be separated by comma

Is this what you’re trying to do?

const codesArr = obj.codes.map(c => c.name)
console.log(codesArr.join(','))

Kind of but it’s printing like this: John,Ashley,Travis,Jack

I am wondering if I can get:

"John","Ashley","Travis","Jack"

const codesArr = obj.codes.map(c => `"${c.name}"`)

The requirement of code: "John","Ashley","Travis","Jack" doesn’t seem to be a valid notiation for a webservice.
Most web services use the JSON notation, so I recommend using JSON.stringify to create your desired output.

var data = {
  code: []
};
obj.codes.forEach(function (code) {
  data.id = code.ID;
  data.code.push(code.name);
});
var str = JSON.stringify(data);
console.log(str);
// {"code":["John","Ashley","Travis","Jack"],"id":22}

What webservice do you need to pass this information to?

Thanks Paul. You are right. I figured out that this output is the one which is needed "John, Ashley,Travis,Jack" which was the first answer from @mawburn.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.