0

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.

blekione
  • 10,152
  • 3
  • 20
  • 26

3 Answers3

1

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);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

You can use Object.values to get the entries in the parent object.

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]);
});
Musa
  • 96,336
  • 17
  • 118
  • 137
  • I forgot to add that this code is running as jjs Nashorn script and for some reasons it doesn't recognise `Object.values` as a valid function, but your code is actually what I want to achieve. – blekione Feb 09 '18 at 18:14
0

You can try using JToken also -

 using Newtonsoft.Json.Linq;    

 JToken.Parse(response.Content)
.SelectTokens("root.parent");
Himalaya Garg
  • 1,525
  • 18
  • 23