简体   繁体   中英

How to iterate over JavaScript object when value of a value can be object?

Edited question . Thanks to @WiktorZychla for waking my Monday brain about recursion. Following code is now working as it should.

If I have an object like this dummy here:

const dummy = {
    a: 1,
    b: 2,
    c: {
        d: 3,
        e: {
            f: 4
        }
    },
    g: 5
};

I can iterate trough it with:

const xavier = (value, s) => {
  for (const key in value) {
    if (value.hasOwnProperty(key)) {
      if (typeof value[key] === 'object' && value[key] !== null) {
        xavier(value[key], s + '.' + key);
      } else {
        console.log(s + '.' + key + ' ' + value[key]);
      }
    }
  }
};

This now prints the following:

.a 1
.b 2
.c.d 3
.c.e.f 4
.g 5

after hard work i make a function that loop on any object: this will definitly iterate on how much level you want please just take a look on it

 arr = []; obj = { a: 1, b: 2, c: { d: 3, e: { f: 4 } } } function iter(x){ for(i in x){ if(typeof(x[i])=="object"){ iter(x[i]); }else{ arr.push(x[i]); }}} iter(obj); document.write(arr.join(',')); 
 <!DOCTYPE html> <html> <body></body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM