简体   繁体   中英

angularjs - javascript - Convert object values from string to array structure

I'm studying some complex cases on json convert with js, and I have a situation like this:

I got this:

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

And I want to convert to this:

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

I'm already doing this conversion on a revert case with this great solution by @RomanPerekhrest, I want to get back the same structure, but I tried a few ways with no success, Roman's solution:

 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)); 

 var obj = { "page": "POST,PUT:122", "news": "PUT" }; var rez={}; Object.keys(obj).forEach(function(key){ obj[key].split(",").forEach(function(value){ var item = value.split(":"); var obj=rez[key] || {}; if (item.length>1){ obj[item[0]]=isNaN(Number(item[1])) ? item[1] : Number(item[1]); rez[key]=obj; }else{ obj[item[0]]=[item[0]]; rez[key]=obj; } }); }); console.log(rez); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM