siva shanker siva shanker - 2 months ago 7
Javascript Question

Concatenate object and key value and get the length

Below is my sample data in which I am trying to access the key and get length, 'xxxxxx20160929' key is dynamic:

"resultData": [{
"a": "124",
"b": "0",
"c": "0",
"d": {
"e": "6",
"f": "en",
"xxxxxx20160929": [{
"ID": "yyyyyyyy"
},
{
"ID": "fffff"
}
]
}
}]


Below is the code I have tried:

var m = 1;
var schedule = [];
// looping to get key value 'xxxxxx20160929'
$.each(response.resultData['0'].d, function(key, value) {
if (m == 3) {
//got value 'xxxxxx20160929'
schedule.push(key);
//trying to check the length of 'xxxx20160929'
console.log(response.resultData['0'].d.key.length);
}
m++;
});


My expected output is 2, because 'xxxxxx20160929' is looping 2 times.

Answer

This assumes that the interesting dynamic key can be found ALWAYS at a fixed position in the d object. This is VERY brittle. If there is a better way to signal for the key (such as it always starts with "xxxxxx" then I'll update.

var data = {
  "resultData": [
    {
      "a": "124",
      "b": "0",
      "c": "0",
      "d": {
          "e": "6",
          "f": "en",
          "xxxxxx20160929": [
            {"ID": "yyyyyyyy" },
            {"ID": "fffff"}
         ]
      }
    }
  ]
};

data.resultData.forEach(function(item){
  var _key = Object.keys(item.d)[2];
  var _value = item.d[_key];
  console.log("Key: " + _key);
  console.log("Children: " + _value.length);
});