How to expand single level nested hashes on the fly?

Viewed 68

I have an object where a few of the keys are nested single level hashes. In this example only b is nested.

const j = {
  a: 'A',
  b: {
    bb: 'BB',
    bbb: 'BBB',
    },
  c: 'C'
};

Question

What I am looking for is a way to loop over the object and if a key is a nested object, then print its keys instead.

a
bb
bbb
c

Does anyone know how to do that?

3 Answers

You can do this recursively:

function printKeys(obj) {
    for (const [key, val] of Object.entries(obj)) {
        if (typeof val === "object") {
            printKeys(val);
        } else {
            console.log(key);
        }
    }
}

If you only have one level of nesting at most, @blex's answer is probably the better one.

You could do it with Object.entries and flatMap:

const j = { a: 'A', b: { bb: 'BB', bbb: 'BBB' }, c: 'C' };

function getOneLevelKeys(obj) {
  return Object.entries(obj)
    .flatMap(([key, value]) => typeof value === "object" ? Object.keys(value) : key);
}

console.log( getOneLevelKeys(j) );

You can use a recursive flatMap with Object.keys.

const j = {
  a: 'A',
  b: {
    bb: 'BB',
    bbb: 'BBB',
    },
  c: 'C'
};
const getKeys = o => Object.keys(o).flatMap(x => o[x] === Object(o[x]) 
      ? getKeys(o[x]) : x);
console.log(getKeys(j));

Related