javascript - 在另一个 json 对象(不是数组)中获取 json 对象

标签 javascript json parent names

我得到了这个结构:

{
"parent": {
      "child-parent-1": {
            "att1": null,
            "att2": null,
      },
      "child-parent-2": {
            "att1": null,
            "att2": null,
      }
 }}

我需要得到的是“child-parent-1”和“child-parent-2”的名字,但不知道它们的名字...因为它们是动态生成的,就像哈希码 (askdl1km2lkaskjdnzkj2138)。

尝试迭代,但我无法让它工作。我总是得到子属性(键/值对)。或者包含所有对象的整个父对象。需要获取我上面提到的 parent 姓名。

我该怎么做?

提前致谢。

最佳答案

迭代对象应该有效:

var parents = {
    "parent": {
        "child-parent-1": {
            "att1": null,
            "att2": null,
        },
        "child-parent-2": {
            "att1": null,
            "att2": null,
        }
    }
}

for(var key in parents.parent){       // parents.parent because the children are in a object in `parents`
    console.log(key);                 // child-parent-1 / child-parent-2
    console.log(parents.parent[key]); // The objects themselves.
}

对我来说,这个日志:

// child-parent-1
// Object {att1: null, att2: null}
// child-parent-2
// Object {att1: null, att2: null}

关于javascript - 在另一个 json 对象(不是数组)中获取 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14586501/

相关文章:

javascript - Ajax 请求链接/嵌套?

json - 如何使用命令行计算 JSON 对象中的项目?

javascript - 每秒检查一次json,数据变化时刷新页面

javascript - 将未定义的 JSON 转换为新的 JSON 对象

jquery - 如何用jQuery替换父div的内容

javascript - 列出元素和 jquery

javascript - 我可以在运行时修改 Javascript 库吗?

javascript - 没有 Chrome 的 Chrome ?

jquery - 如果选中复选框,则将类添加到父元素

javascript - parent.opener 在 webview Android 中不起作用