Lucas Santos Lucas Santos - 4 months ago 20
JSON Question

angularjs - javascript - Convert object values from array to string

I'm facing some problems with objects, json and etc in js. If some one can help me with something, it would be amazing! :)

I have an object, that I can't change, like this:

{
"page": [
"POST",
"DELETE"
],
"news": [
"PUT"
]
}


I want to convert to be like this:

{
"page": "POST, DELETE",
"news": "PUT"
}


So I want the object values (arrays) to be string, I also tried toString(), String(), JSON.stringify, and other approaches from the internet, (maybe I had not done it right) but none worked for me, I'm kind of new on dealing with these type of data, so if some one can help me, TKS!! :D

EDIT:



And in the case I got this structure:

{
"page": {
"POST": [
"POST"
],
"PUT": 122
},
"news": {
"PUT": [
"PUT"
]
}
}


How can I convert to be like:

{
"page": "POST, PUT:122",
"news": "PUT"
}

Answer

If you want to modify the initial object - it would be enough to use Object.keys and Array.forEach functions:

var obj = {
  "page": [
    "POST",
    "DELETE"
  ],
  "news": [
    "PUT"
  ]
};

Object.keys(obj).forEach(function(k) {
  obj[k] = obj[k].join(",");
});

console.log(JSON.stringify(obj, 0, 4));