Steps for adjusting the structure of an array of objects according to the ParentID

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{
        ....
     }
 });

Answer №1

To narrow down your list of orders, you first identify the "rootOrder" instances that have one or more children attached to them. Afterwards, you refine the list further by comparing the ParentId with the root.pID

// input
const JsonData = {
  info: {
    Factorid: 197325,
    productList: [
      {
        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,
        Description: "",
        productid: "1428648",
        UnitPrice: "60000",
      },
      {
        pID: 794551,
        Count: 1,
        ParentID: 0,
        Description: "",
        productid: "1428647",
        UnitPrice: "250000",
      },
      {
        pID: 794526,
        Count: 3,
        ParentID: 794550,
        Description: "",
        productid: "1428548",
        UnitPrice: "600000",
      },
      {
        pID: 794527,
        Count: 1,
        ParentID: 0,
        Description: "",
        productid: "1428542",
        UnitPrice: "400000",
      },
    ],
  },
};

function processOrders(productList) {
  const mainProducts = productList.filter((product) => product.ParentID === 0);

  return mainProducts.map((mainProduct) => {
    const subProducts = productList.filter((product) => product.ParentID === mainProduct.pID);

    return {
      ...mainProduct,
      children: subProducts.length ? subProducts : "",
    };
  });
}

// output
const processedJsonData = {
  ...JsonData,
  info: {
    ...JsonData.info,
    productList: processOrders(JsonData.info.productList),
  },
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Delete the initial instance of a specific element with JavaScript or Lodash

I am working with an array that looks like this - ["a", "a", "b", "c", "d", "e"] My goal is to filter this array in a way that removes only the first occurrence of each element. Based on the exa ...

Filtering Jquery datatable results by text

In order to filter records from a jQuery data table, I have utilized the following code. The format for my data table is as follows: var aDataSet = [['1', 'GOld', 'G-110,G-112,G-123', 'G1-001,G1-005,G1-008'], ...

modifying variable values does not impact what is displayed on the screen

I'm currently facing an issue with AngularJS. I have two HTML blocks within an ng-repeat and I need to display one of them at each step. <div class="col-md-3" style="margin-top:80px" ng-init="checkFunction()"> <div id="left_group_stage"& ...

Secure your arrays with mysqli escape string functionality

I am struggling with escaping arrays in PHP. I am currently using array_map in combination with mysqli_real_escape_string. My arrays are structured like this: $_post['countries']; $_post['categories']; . . How can I properly escape t ...

What is the process for setting a cookie in Next.js from a different backend server?

I have encountered an issue with my Node.js API built using Express.js. The cookie I set works perfectly fine on Postman, but for some reason, it is not functioning properly in Next.js. I set the cookie when a user logs in, but it is not appearing in the b ...

Scraping multiple websites using NodeJS

I have been immersing myself in learning NodeJS and experimenting with web scraping a fan wikia to extract character names and save them in a json file. I currently have an array of character names that I want to iterate through, visiting each URL in the a ...

Creating a custom ID for a Firebase POST request

Is it possible to assign a custom ID in Firebase when using the POST method? For example: { "users": { "user_one": { "username": "jdoe", "password": "123" } } } I'm currently working on a Vue.js project and I want to save ...

Determine the amount of time that can be allocated based on the attributes contained within the object

I am faced with a JSON structure like the one below: var meetings = [ { id: '1', start_time: "2020-11-15T08:30:00+00:00", end_time: "2020-11-15T14:15:00+00:00" }, { id: '2', start_time: &quo ...

AngularJS Issue: The function 'FirstCtrl' is missing and is undefined

Currently, I am enrolled in the AngularJS course on egghead.io and have encountered an issue that seems to be a common problem for others as well. Despite trying various solutions found here, none seem to work for me. In the second lesson video, the instru ...

Guide on Organizing Information in Next.js

I have an online store and I am looking to organize my data by categories. Initially, I tried using APIs for this purpose but it ended up putting a strain on my server. So now, I am attempting to use Redux to store the data and filter it from there. Howeve ...

Testing inherit from a parent class in a unit test for Angular 2

Trying to create a unit test that checks if the method from the base class is being called This is the base class: export abstract class Animal{ protected eatFood() { console.log("EAT FOOD!") } } Here is the class under test: export ...

Just starting out with callback functions (using a callback as an argument)(Javascript)

Hello everyone, I'm a beginner here and I have a question about callback functions. Upon reading about them, I felt like I understood the concept. However, when I attempted to implement one in my code, things didn't go as planned. functio ...

What is the best way to arrange this by DateTransaction using a dropdown list?

Requesting assistance from the PHP community! I'm a newbie and in need of your expertise. My task is to create a dropdown list that sorts a table based on the DateTransaction column, with options ranging from January to December. Here is the code sni ...

How can I transform this statement into a higher-order function that offers a resource instead of using an object for initialization and destruction?

Starting with this code snippet: convert utilizes svgInjector to start and terminate a resource. export async function convert( serializedSvg: string, svgSourceId: string, containerId: string ): Promise<string> { const svgInjector = new SvgI ...

How can data be sent to an AJAX request using jQuery?

Every time I attempt to send data through ajax, it doesn't seem to pass the data along. $('#savenew').click(function () { var user = <?php echo $user?>; $.ajax({ type: "POST", url: "actions/sub.php", data: user, su ...

Retrieve the response text using native JavaScript

Dealing with the nature of asynchronous XMLHTTPRequest in JavaScript can be tricky. I faced a challenge where I needed to return the responseText value but found it impossible due to this nature. To overcome this, I came up with a workaround by calling a f ...

How to Align Text at the Center of a Line in Three.js

Exploring What I Possess. https://i.sstatic.net/nAtmp.png Setting My Goals: https://i.sstatic.net/svcxa.png Addressing My Queries: In the realm of three.js, how can I transform position x and y into browser coordinates to perfectly align text in th ...

Refreshing Vue by reloading new components and injecting them into the HTMLDOM

Is there a way to make Vue re-initialize itself after inserting a component fetched from an API into the DOM? The component looks like this: <div><My_component /></div> This component is part of a back-end snippet. When inserting it i ...

A Step-by-Step Guide to Clearing JSON Cache

I'm currently utilizing jQuery to read a JSON file. However, I've encountered an issue where the old values are still being retrieved by the .get() function even after updating the file. As I continuously write and read from this file every secon ...

Javascript Callback function not working as expected

I'm attempting to include an anonymous callback function in my code. I know it might seem a bit messy. By typing into the intro section, it triggers the animation using the .typed method with specific parameters. What I'm struggling to do is imp ...