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

msq*_*qar 1 javascript json parent names

我有这个结构:

{
"parent": {
      "child-parent-1": {
            "att1": null,
            "att2": null,
      },
      "child-parent-2": {
            "att1": null,
            "att2": null,
      }
 }}
Run Code Online (Sandbox Code Playgroud)

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

尝试迭代但我无法使其工作.我总是得到子属性(键/值对).或者包含其中所有对象的整个父对象.需要获得我上面提到的父名.

我怎样才能做到这一点?

提前致谢.

Cer*_*rus 5

迭代对象应该工作:

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.
}
Run Code Online (Sandbox Code Playgroud)

对我来说,这个日志:

// child-parent-1
// Object {att1: null, att2: null}
// child-parent-2
// Object {att1: null, att2: null}
Run Code Online (Sandbox Code Playgroud)