从JSON获取元素集合

时间:2018-02-09 17:42:30

标签: javascript json nashorn jjs

我有一个JSON文件,结构如下:

{"root" : {
     "parent" : {
          "childA" : 
              ["element1",
               "element2"],
          "childB" :
              ["element1",
               "element2"]
     }
}

如何从中获取儿童[childA, childB]的集合?

现在我在做什么:

  1. 将JSON文件解析为一个对象(我知道如何做到这一点,建议的响应与此有关)。

  2. 创建集合:

    var collection = [JSON.root.parent.childA, JSON.root.parent.childB];
    collection.forEach(function(child) {
        print(child[0])
    });
    
  3. 打印"element1"

    我是JavaScript新手,但我相信有更好,更通用的方式来实现第2点。

    编辑: 我忘了添加这个Java脚本在Nashorn jjs脚本中使用。

2 个答案:

答案 0 :(得分:1)

只需使用Object.keys()



var data = {"root" : {
     "parent" : {
          "childA" : 
              ["element1",
               "element2"],
          "childB" :
              ["element1",
               "element2"]
     }
   }
};
var collection = [];
for (var childIndex in data.root.parent){
  data.root.parent[childIndex].every(child => collection.push(child));
};
console.log(collection);




答案 1 :(得分:1)

您可以使用Object.values获取父对象中的条目。

var data = {"root" : {
     "parent" : {
          "childA" : 
              ["element1",
               "element2"],
          "childB" :
              ["element1",
               "element2"]
     }
   }
};


var collection = []; 
for (var o in data.root.parent){
    collection.push(data.root.parent[o]);
}
collection.forEach(function(child) {
    console.log(child[0]);
});

相关问题