【发布时间】:2019-10-01 06:53:31
【问题描述】:
现在我正在使用 JSON 对象来比较信息,我不知道是否有办法获得特定键的深度级别。
例如,我有这个 JSON 对象:
{
hi : "everyone",
hereIs : {
an : "Object"
}
}
而且我需要在 for ... in 循环中知道每个键的深度级别:
hi is in level 0
hereIs is in level 0
an is in level 1
我目前拥有的是:
// Loop through the first object
for (key in obj1) {
if (obj1.hasOwnProperty(key)) {
compare(obj1[key], obj2[key], key);
}
}
如果使用“比较”功能来验证对象中的信息是否相等,如果不相等,则将信息添加到第三个对象中,我想知道的是如何获得密钥的级别在 obj1 中并将其传递给“比较”函数。
感谢您的帮助。
【问题讨论】:
-
这应该是一个简单的递归函数。
-
StackOverflow 不是免费的编码服务。你应该try to solve the problem first。请更新您的问题以在minimal reproducible example 中显示您已经尝试过的内容。如需更多信息,请参阅How to Ask,并拨打tour :)
标签: javascript object tree key depth