angularjs - javascript - Convert object values from array to string -
i'm facing problems objects, json , etc in js. if 1 can me something, amazing! :)
i have object, can't change, this:
{ "page": [ "post", "delete" ], "news": [ "put" ] }
i want convert this:
{ "page": "post, delete", "news": "put" }
so want object values (arrays) string, tried tostring(), string(), json.stringify, , other approaches internet, (maybe had not done right) none worked me, i'm kind of new on dealing these type of data, if 1 can me, tks!! :d
edit:
and in case got structure:
{ "page": { "post": [ "post" ], "put": 122 }, "news": { "put": [ "put" ] } }
how can convert like:
{ "page": "post, put:122", "news": "put" }
if want modify initial object - enough use object.keys
, 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));
additional solution complex case:
var obj = { "page": { "post": [ "post" ], "put": 122 }, "news": { "put": [ "put" ] } }; object.keys(obj).foreach(function (k) { var innerkeys = object.keys(obj[k]), items = []; innerkeys.foreach(function(key) { items.push((array.isarray(obj[k][key]))? key : key + ":" + obj[k][key]); }); obj[k] = items.join(","); }); console.log(json.stringify(obj, 0, 4));
Comments
Post a Comment