简体   繁体   中英

Parsing a JSON result and creating a custom object from it

UPDATE

All the solutions in this post answer my question, but I can mark only one as excepted answer...

I have this JSON result:

[
   { 
      "unsorted1":[7,7,10,3,3]
   },
   {
      "unsorted2":[8,9,3,10,6]
   }
]

I would like to make an array in JavaScript that has each the "unsorted1" and "unsorted2" as keys, the [7,7,10,3,3] and [8,9,3,10,6] must remain in JSON format. An object like That unsorted1: [7,7,10,3,3] and unsorted2: [8,9,3,10,6]

This is what I get in the browser using the console.log(JSON.parse(returnVar)); the returnVar parameter holds my JSON result from above.

在此处输入图片说明

I read a lot and tried a lot, but nothing comes close to what I want. Somehow I can't get it done.

I tried modifying this code with no success

var resultObj = {};
for (var key in returnVar) {
    if (returnVar.hasOwnProperty(key)) {
        var val = returnVar[key];
        console.log("val: " + val);
        var keyName = Object.keys(val);
        console.log("key Name: " + keyName);
        for (var keykey in val) {
            if (val.hasOwnProperty(keykey)) {
                var valval = val[keykey]
                resultObj[keyName] = JSON.stringify(valval);
            }
        }
    }
}

you can try this code:

var response = [
  { 
    "unsorted1":[7,7,10,3,3]
  },
  {
    "unsorted2":[8,9,3,10,6]
  }
];

var customObject = response.reduce(function(result, item) {
  var keys = Object.keys(item);

  if(keys.length) {
    result[keys[0]] = item[keys];
  }

  return result;
}, {});

 var a = [ { "unsorted1": [7, 7, 10, 3, 3] }, { "unsorted2": [8, 9, 3, 10, 6] } ] var b = {} a.forEach(function(x) { Object.keys(x).forEach(function(y) { b[y] = JSON.stringify(x[y]) }) }) console.log(b); 

 //if the Json result is an object - this is how you parse it var objJson = [{ "unsorted1": [7, 7, 10, 3, 3] }, { "unsorted2": [8, 9, 3, 10, 6] }]; function parse() { if (Array.isArray(objJson) === true) { objJson.map(function(i) { //alert(JSON.stringify(i)); console.log(JSON.stringify(i)); }); }; } parse(); //if your json result is a string - this is how you do it var strJson = "[{\\"unsorted1\\": [7, 7, 10, 3, 3]}, {\\"unsorted2\\": [8, 9, 3, 10, 6]}]"; //dont worry about the escaped quotes here - this is a string that is represented here.. but it will work if your JSON result is a string. function parseString() { var objJson = JSON.parse(strJson); if (Array.isArray(objJson) === true) { objJson.map(function(i) { //alert(JSON.stringify(i)); console.log(JSON.stringify(i)); }); }; } parseString(); 

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