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.

Peter DeWeese
  • 18,141
  • 8
  • 79
  • 101
coool
  • 8,085
  • 12
  • 60
  • 80
  • 3
    You have a JavaScript object, not JSON. If you know that's your object structure, you'd just do `user.personal.age` – I Hate Lazy Oct 16 '12 at 05:21
  • possible duplicate of [I have a nested data structure / JSON, how can access a specific value?](http://stackoverflow.com/questions/11922383/i-have-a-nested-data-structure-json-how-can-access-a-specific-value) – Felix Kling Oct 16 '12 at 05:24
  • 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 '12 at 05:24
  • The documentation also explains which arguments are passed to the callback: http://underscorejs.org/#each. – Felix Kling Oct 16 '12 at 05:25
  • I don't know if underscore has something specific, but you could easily create a recursive function, so whenever you find an object, it would just recursively call that function, passing the found object. – I Hate Lazy Oct 16 '12 at 05:27
  • 2
    `function deep(obj) { _.each(obj, function(item) { if (item && typeof item === "object") deep(item); else console.log(item); }); }` – I Hate Lazy Oct 16 '12 at 05:27

1 Answers1

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)
       }) 
    }
})
SMathew
  • 3,993
  • 1
  • 18
  • 10