Search code examples
javascriptjsonnashornjjs

Get collection of elements from JSON


I have a JSON file with the structure as below:

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

How can I get a collection of children [childA, childB] from it?

For now what I'm doing:

  1. Parse the JSON file to an object (I know how to do that and suggested response is about this).

  2. Create the collection:

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

to print "element1".

I'm new to JavaScript but I believe there is a better and more generic way to achieve the point 2.

EDIT: I forgot to add that this Java Script is used inside Nashorn jjs script.


Solution

  • Simply use Object.keys() for this:

    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);