Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

Define a print function

functionprint(obj, prefix) {
  prefix = prefix || 'obj';
  returnObject.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"

Post a Comment for "How To Iterate Through All Keys & Values Of Nested Object?"