user2435860
user2435860

Reputation: 798

How to iterate through all keys & values of nested object?

I am developing a web application in javascript (both on the server and client side). I am sending back and forth data as json, and I want to be able to parse it on the other side. The problem is that I have several levels of nested objects inside, so this is where I am stuck. For example, I am sending the following data:

var data = {};
data.title = "My Title";
data.metric = {
   fact : "Malicious code detected",
   technique : "XSS"
};
data.subject = {
   userType : "ADMIN",
   userName : "Jack",
   clientNumber : "000",
   terminal : "192.168.1.1"
};
data.context = {
   environment : {
      session : "00",
      hostname : "mainServer",
      sysType : "production"
   },
   resource : {
      wpt : "DIA",
      pid : "1024"
   }
};

On the other side, when I receive it, I just want to be able to completely loop through this object, and print its contents. I have seen a lot of similar questions on stackoverflow, but none of them have been helpful. Here is what I have done so far:

function display(data) {
    var resp = "";
    var prop = null;
    var dataJSON = JSON.parse(data);

    for (prop in dataJSON) {
        if (patternJSON.hasOwnProperty(prop)) {
            resp += "obj" + "." + prop + " = " + dataJSON[prop] + "\n";
        }
    }
    return resp;
}

But I do not know how to make it automatically go deeper, no matter the number of levels. Can somebody point me to the right direction please? Any help would be greatly appreciated! 10x

Upvotes: 3

Views: 2778

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Define a print function

function print(obj, prefix) {
  prefix = prefix || 'obj';
  return Object.keys(obj).reduce(function(acc, key){
      var value = obj[key];
      if(typeof value === 'object') { 
          acc.push.apply(acc, print(value, prefix + '.' + key));
      }
      else { 
          acc.push(prefix + '.' + key + ' = ' + value);
      }
      return acc;
  }, []);
}

And use it like this print(data).join('\n').

"obj.title = My Title
obj.metric.fact = Malicious code detected
obj.metric.technique = XSS
obj.subject.userType = ADMIN
obj.subject.userName = Jack
obj.subject.clientNumber = 000
obj.subject.terminal = 192.168.1.1
obj.context.environment.session = 00
obj.context.environment.hostname = mainServer
obj.context.environment.sysType = production
obj.context.resource.wpt = DIA
obj.context.resource.pid = 1024"

Upvotes: 5

Related Questions