Reputation: 10590
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:
Parse the JSON file to an object (I know how to do that and suggested response is about this).
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.
Upvotes: 0
Views: 3422
Reputation: 1609
You can try using JToken also -
using Newtonsoft.Json.Linq;
JToken.Parse(response.Content)
.SelectTokens("root.parent");
Upvotes: 0
Reputation: 97682
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]);
});
Upvotes: 1
Reputation: 30739
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);
Upvotes: 1