【问题标题】:get json objects inside another json object (not array)在另一个 json 对象(不是数组)中获取 json 对象
【发布时间】:2013-01-29 15:34:08
【问题描述】:

我得到了这个结构:

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

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

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

我该怎么做?

提前致谢。

【问题讨论】:

标签: javascript json parent names


【解决方案1】:

迭代对象应该可以工作:

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}

【讨论】:

  • 是的,这是一个愚蠢的问题,尝试了很多东西,但没有尝试过,哈哈。警报(键);做了这件事:D
猜你喜欢
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 2012-08-29
  • 2021-08-07
  • 2018-09-22
相关资源
最近更新 更多