-3

How can i iterate through a nested object in a object without creating a function and without using ECMASCRIPT new properties like Object.entries and the like. That including not using JSON. Just Vanilla javascript. Rather with pure .notation or square brackets (i would like to understand how it would work and not just solve my problem). This is my code.

var obj = { name1:{fname:'jack',sname:'smith',age:31},
            name2:{fname:'john',sname:'dill',age:55}}

How can i print every key with every value using a for in loop

Yossi Sternlicht
  • 740
  • 1
  • 6
  • 17

2 Answers2

1

var obj = {
  name1: {
    fname: 'jack',
    sname: 'smith',
    age: 31
  },
  name2: {
    fname: 'john',
    sname: 'dill',
    age: 55
  }
}

for (let property in obj) {
  let innerObj = obj[property];
  console.log(`${property} : ${obj[property]}`)
  for (let innerProperty in innerObj) {
    console.log(`${innerProperty} : ${innerObj[innerProperty]}`)
  }
}

Hi Joe. A for..in loop works like this. You create the loop: for (let property in obj) and while you are in it, you can access the object's property values like obj[property]. In this example, I created an inner loop because your outer objects have attribute values which are also objects. Hope this helps! Try reading up on for...in here.

It might be worth pointing out here that the way you have organized this data isn't ideal. It would be much simpler if you didn't have a name property in the object, and instead just used an array. Then your data would look like:

var array = [{ fname: 'jack', sname: 'smith', age: 31 },
{ fname: 'john', sname: 'dill', age: 55 }];
Katie.Sun
  • 711
  • 3
  • 15
  • yeah that works but i dont understand what the dollar sign does – Yossi Sternlicht Dec 03 '18 at 14:49
  • It's just a way of making it so you can use JavaScript variables directly in a string without using concatenation like `'this is a string ' + variable`. You have to use it with ` ` ` – Katie.Sun Dec 03 '18 at 14:52
0

if i got it correct , is something like this you are looking for?

for(var property in obj) {
    for(var property2 in obj[property]) {
        console.log('key:' + property2 + '   ' + 'value:' + obj[property][property2]);
    }
}
rule
  • 281
  • 1
  • 8