How to expand single level nested hashes on the fly?

若如初见. 提交于 2021-01-28 05:01:06

问题


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?


回答1:


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.




回答2:


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) );



回答3:


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));


来源:https://stackoverflow.com/questions/65571240/how-to-expand-single-level-nested-hashes-on-the-fly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!