0

I have a json object

user = { name: "somename", personal : { age:"19",color:"dark"}}
_.each(user,function(value){ if(isNaN(value){console.log(value)} )

How to get to the nested object value.

6
  • 3
    You have a JavaScript object, not JSON. If you know that's your object structure, you'd just do user.personal.age Oct 16, 2012 at 5:21
  • I would like to keep it generalized..as well as I would like to know if in underscore if it is possible to loop through at the nested level
    – coool
    Oct 16, 2012 at 5:24
  • The documentation also explains which arguments are passed to the callback: underscorejs.org/#each. Oct 16, 2012 at 5:25
  • 2
    function deep(obj) { _.each(obj, function(item) { if (item && typeof item === "object") deep(item); else console.log(item); }); } Oct 16, 2012 at 5:27

1 Answer 1

1

Something like this will work. If you expect even more deeply nested objects, then create a recursive function. _.isObject(val) is the key here.

_.each( {name: "somename", personal : { age:"19",color:"dark"}}, function(val) {
    if (_.isObject(val)) {
       _.each(val, function(v) {
            console.log(v)
       }) 
    }
})

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.