Dhana Dhana - 7 months ago 16
Javascript Question

How to get json values for keys from json nested structure?

I am trying to get the specific json values for the specific keys from the json structure. I have tried the following:

var jsonstring;
jsonstring = JSON.stringify(myjsonObjectArray);
alert(jsonstring);//giving the below json structure

jsonstring = [{
"key01": [10, "Key01 Description"],
"key02": [false, "It's a false value"],
"key03": [null, "Testing Null"],
"key04": ["tests", "Another Test Value"],
"key05": [
[25, 50], "Some testing values"
]
}, {
"key10": [100, "Key10 Value"],
"key11": [true, "It's a true value for key11"],
"key12": [null, "key12 values is Null"],
"key13": ["Testing", "Another Test Value for key13"],
"key14": [
[10, 20], "Some other testing values"
],
"key15": ["Test Name", "Name of the key15"]
}]


but I need like below structure:

jsonstring = [{
"key01": 10,
"key02": false,
"key03": null,
"key04": "tests",
"key05": [25, 50]
}, {
"key10": 100,
"key11": true,
"key12": null,
"key13": "Testing",
"key14": [10, 20],
"key15": "Test Name"
}]


How can I get like above structure(means I need only single values, don't need the second values/multiple values for the respective keys from the structure) ? Please help me and thanks in advance.

Answer

Use Array#map which creates a new array with the results of calling a provided function on every element in this array and to get the first item from array, manipulate it using for..in loop and extract first-index-item from array.

var jsonstring = [{
  "key01": [10, "Key01 Description"],
  "key02": [false, "It's a false value"],
  "key03": [null, "Testing Null"],
  "key04": ["tests", "Another Test Value"],
  "key05": [
    [25, 50], "Some testing values"
  ]
}, {
  "key10": [100, "Key10 Value"],
  "key11": [true, "It's a true value for key11"],
  "key12": [null, "key12 values is Null"],
  "key13": ["Testing", "Another Test Value for key13"],
  "key14": [
    [10, 20], "Some other testing values"
  ],
  "key15": ["Test Name", "Name of the key15"],
  "key16": null, //Test Data
  "key17": 'Fake Name' //Test Data
}];
var op = jsonstring.map(function(item) {
  for (var i in item) {
    item[i] = Array.isArray(item[i]) ? item[i][0] : item[i]; //If `item[i]` is not an array
  }
  return item;
});
console.log(op);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>