TalG TalG - 2 months ago 5
Javascript Question

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.

enter image description here

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

Answer

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

Comments