1

I want to get the individual values of JSON Object keys as well as of its elements too with the help of the iteration

My json will looks like this:-

var a=
{
    "HYDROGEN": {
        "atomic_number": 1,
        "abbreviation": "H",
        "atomic_weight": 1.008
    },
    "HELIUM": {
        "atomic_number": 2,
        "abbreviation": "He",
        "atomic_weight": 4.003
    }}
Jaini
  • 90
  • 10
  • you can read here for more information http://stackoverflow.com/questions/14028259/json-response-parsing-in-javascript-to-get-key-value-pair – Akashii Apr 01 '17 at 11:33
  • @ThanhTùng thanx but i solved it by my own – Jaini Apr 01 '17 at 12:06

2 Answers2

1
var a=
{
    "HYDROGEN": {
        "atomic_number": 1,
        "abbreviation": "H",
        "atomic_weight": 1.008
    },
    "HELIUM": {
        "atomic_number": 2,
        "abbreviation": "He",
        "atomic_weight": 4.003
    },
    "HELIUM": {
        "atomic_number": 2,
        "abbreviation": "He",
        "atomic_weight": 4.003
    }}

  for (i=0;i<1;i++)
  {
  console.log(Object.keys(a)[i])
  console.log(a[Object.keys(a)[i]].atomic_number)
  console.log(a[Object.keys(a)[i]].atomic_weight)
  console.log(a[Object.keys(a)[i]].abbreviation)
}
Jaini
  • 90
  • 10
0

You can retrieve the [keys] and [values] of your {a} object dynamically like this:

for (var sIndexKey in a) {
    if (a.hasOwnProperty(sIndexKey) === true) {
        var oJsonData = a[sIndexKey]; // in this case the 2 objects inside your {a} object
        var sObjectKeys = Object.keys(oJsonData); //e.g atomic_number / abbreviation / atomic_weight
        for (var iIndex = 0; iIndex < sObjectKeys.length; iIndex++) {
            var sJsonKeys = sObjectKeys[iIndex];
            var sJsonValues = oJsonData[sJsonKeys];
            console.log(sJsonKeys);
            console.log(sJsonValues);
        }
    }
}

Here's a jsfiddle for further reference: http://jsfiddle.net/q37ehka9/

Hope this helps for your case

Marylyn Lajato
  • 1,171
  • 1
  • 10
  • 15