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

前端 未结 1 1543
孤城傲影
孤城傲影 2021-01-20 18:28

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 othe

相关标签:
1条回答
  • 2021-01-20 19:21

    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"
    
    0 讨论(0)
提交回复
热议问题