0

I need some help with JavaScript. The Problem is that i have a JSON data similar as show in follow,but the problem is that i am not able to access all the objects. With my function i am able to access ["x","y","z"], but i am not able to get others "p,q,r.k,a".Can anyone help me to get this thing fixed, please dont use Object.Keys().I dont know how to iterate inside Json Data.


var Objectkeys = function(obj){
    a = []
    for(var prop in obj){
    if(obj.hasOwnProperty(prop)){
        a.push(prop)
        }
    }
    return a;
};
var obj = {
    x: 1,
    y: 2,
    z: {
        p: "Hello",
        q: "Master",
        r: {
            k: "Rotten",
            a: "apple"
        }
    }
};
window.onload = function () {
console.log(Objectkeys(obj));
//console.log(Object.keys(obj));
}

Thank you

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • be aware that what you present here is not JSON, it is simply a JavaScript object. JSON is not JavaScript but a serialization format (which has JavaScript compatible syntax). In JavaScript, a variable containing JSON would be of type string. After parsing/evaluating that string you would get the object. – chiccodoro Mar 21 '14 at 08:12

3 Answers3

0

You need to iterate nested object also:

var Objectkeys = function(obj){
        a = []
        for(var prop in obj){
            if (obj.hasOwnProperty(prop)) {
                a.push(prop);
                if (typeof obj[prop] === 'object') {
                    a = a.concat(Objectkeys(obj[prop]));
                }
            }
        };
        return a;
    };
Damian Krawczyk
  • 2,241
  • 1
  • 18
  • 26
0

If grabbing the object keys is all you're after you can use a recursive function:

function getKeys(obj) {
  var arr = [];
  (function loop(obj) {
    for (var k in obj) {
      if (obj.hasOwnProperty(k)) {
        arr.push(k);
        if (typeof obj[k] === 'object') {
          loop(obj[k]);
        }
      }
    }
  }(obj));
  return arr;
}

console.log(getKeys(obj)); // ["x", "y", "z", "p", "q", "r", "k", "a"]

Demo.

Andy
  • 61,948
  • 13
  • 68
  • 95
-1

I'm not familiar with js, but dont you have to check first if a propertys contains objects and if yes iterate trough those? So a for statement in a if statement?

SaifDeen
  • 862
  • 2
  • 16
  • 33