I have a Json string like this:
var json = "[{"Id":"1234",
"FirstName":"One",
"Index":"32",
"Type":"t1",
"Children":[{"Id":"976","FirstName":"Two","Index":"32","Type":"t2",
"Children":[{"Id":"428",
"FirstName":"Three",
"Index":"32",
"Type":"t3",
"Children":[],
"ParentId":"f235"}],
"ParentId":"f826"}],
"ParentId":"0000"}]"
I want to create a number of objects with only the fields Id,FirstName,Children, not Index and Type. Each Object has a number of child Services as well.
So obj1 will have properties Firstname, ParentId and Children and if you drill down to its Children it will have another object with Id , firstname , ParentId , and for this if we drill down there are no more Children
I began by doing something like
var servicejson = JSON.parse(jsonStr);
for (let i = 0; i < servicejson).length; i++) {
var parentnode = {
Id: servicejson[i].Id,
FirstName: servicejson[i].JsonValue,
ParentId: servicejson[i].ParentId,
};
//check if children
if (servicejson[i].Children.length > 0) {
//do something here ??
}
}
There will be one Object and within that will be a Child , and withing that Child there is another Child node. I got stuck assigning these to the Object or pushing onto an array on the Object as I assume it may need a recursive call to assign the Children array and this is where i need some help Any ideas on how I can to do this ?
you can do something like this
var json = [{"Id":"1234",
"FirstName":"One",
"Index":"32",
"Type":"t1",
"Children":[{"Id":"976","FirstName":"Two","Index":"32","Type":"t2",
"Children":[{"Id":"428",
"FirstName":"Three",
"Index":"32",
"Type":"t3",
"Children":[],
"ParentId":"f235"}],
"ParentId":"f826"}],
"ParentId":"0000"}]
const transform = ({Id, FirstName, Children}) => ({
Id,
FirstName,
Children: Children.map(transform)
})
const result = json.map(transform)
console.log(result)