1

How to enumerate object like below ? I don't know keys in advance, could be much more

{ '10.193.105.1': 
   { location: '02123',
     hostname: 'A0C2',
     contact: 'root@localhost' },
  '10.199.107.1': 
   { location: '01164',
     hostname: 'cp11',
     contact: 'me' } }
1
  • Object.keys(obj).forEach... Commented Nov 13, 2015 at 20:21

1 Answer 1

3

Object.keys gives you the object keys. Nest and loop

var obj = {
  '10.193.105.1': {
    location: '02123',
    hostname: 'A0C2',
    contact: 'root@localhost'
  },
  '10.199.107.1': {
    location: '01164',
    hostname: 'cp11',
    contact: 'me'
  }
};

Object.keys(obj).forEach( function(key) {  //level one
    var child = obj[key];
    console.group(key);
    Object.keys(child).forEach( function (prop) {  //level two
        console.log(prop, ":", child[prop]);
    });
    console.groupEnd(key);  
} );

Sign up to request clarification or add additional context in comments.

4 Comments

what's console.group or console.groupEnd ? In fact I have nodejs
It is logging methods...developer.mozilla.org/en-US/docs/Web/API/Console/group Open up the developer console, Run the code above, look at your console.
sorry, how to do it in nodesjs ?
You do not need it to loop over the object. Add anything you want there. It was just for a demo. If you want to do groups in node use something like this. Again, it is NOT needed. Change it to a normal console and delete the groupEnd line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.