Subhash Subhash - 17 days ago 7
JSON Question

Parsing a JSON Map to object

I'm converting my response that is in JSON to a readable form. The response is a Map.i.e it has a key and value.

data={
"name":"name1"
"mapIWantToConvert":{
"key1":"value1"
"key2":"value2"
"key3":"value3"
}
}


I want to iterate and get all the values of key and value and set them to other var.I am getting keys from a for loop.
this is not working:

var convertedData=data.mapIWantToConvert.key[i];


what am i doing wrong. thank you

output is a again a json file but a different one .

output={
"allDataForkey1":{
"key1":"value1"
}
"allDataForKey2":{
"key2":"value2"
}
}

Answer

If you want to get the values from the convert the mapIWantToConvert key in the response you can do it like so.

var data = {
  "name": "name1",
  "mapIWantToConvert": {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
  }
}

var dataMap = data.mapIWantToConvert;

var values = Object.keys(dataMap).reduce(
  (valueArr, key) => [...valueArr, dataMap[key]], 
  []
)

console.log(values)

Comments