如何动态扩展单层嵌套哈希? [英] How to expand single level nested hashes on the fly?
本文介绍了如何动态扩展单层嵌套哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象,其中一些键嵌套在单个级别的哈希值中.在此示例中,仅嵌套b
.
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
有人知道怎么做吗?
推荐答案
您可以递归执行此操作:
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);
}
}
}
如果最多只有一层嵌套,则@blex的答案可能是更好的答案.
If you only have one level of nesting at most, @blex's answer is probably the better one.
这篇关于如何动态扩展单层嵌套哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文