2

i have nested object:

var obj = {
    nestobj1:{
        title: "some 1 title",
        text: "some text"
    },
    nestobj2:{
        title: "some 2 title",
        text: "some text"
    }
}

I am using for in loop

for ( let s in obj) {
    console.log(s);
}

Console logs strings: nestobj1 and nestobj2. Why? Why it dont returns/logs object ? Why it is string ? Please forgive me i quite new in Javascript.

luk
  • 139
  • 1
  • 2
  • 9
  • 5
    `for...in` loops will pull out the keys in an object, not the values from the object. To look at the nested objects use `obj[s]` – zfrisch Nov 14 '18 at 19:37
  • 3
    The [for in documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) should help you answer this yourself – charlietfl Nov 14 '18 at 19:37

1 Answers1

10

The for...in statement iterates over all enumerable properties of an object.

The way you do it you only get the property name of the object without its value. If you want to get the nested objects (the values) then you need to do it like that:

for ( let s in obj) {
    console.log(obj[s]);
}
Stundji
  • 855
  • 7
  • 17