I need to reorganize an array of objects based on a field called ParentID
.
Here is an example dataset:
var JsonVal = "data": {
"Factorid": 197325,
"orders": [
{
"pID": 794522,
"Count": 1,
"ParentID": 794551,
"Description": "",
"productid": "1428539",
"UnitPrice": "300000",
},
{
"pID": 794525,
"Count": 1,
"ParentID": 794551,
"Description": "",
"productid": "1428543",
"UnitPrice": "600000",
},
{
"pID": 794550,
"Count": 2,
"ParentID": 0,
...
In each object, there is a ParentID. I want to modify the JSON so that if the ParentID is 0, it will be considered a parent and have a new field called children with a value of null. If the ParentID is not 0, then the object is a child of another object that has the same pID as the ParentID of the child Object. The updated JSON structure should look like this:
"data": {
...
children should be included for any parent object and it should always be a string field. I have tried writing some code to handle this but not sure how to proceed.
JsonVal.orders.forEach(orders => {
if(orders.ParentID == 0){
orders.children="";
}else{
....
}
});