Gather an array containing identical IDs within an array, and then form a new array including the ID and name using JavaScript

{ 
   "workRequestCompleted":[ 
      { 
         "number":"4329502",
         "name":"Scheduled Outage Primary Feeder",
         "startDate":"2019-07-01",
         "endDate":"2019-07-10",
         "lastUpdate":"2019-12-01T05:00:00Z",
         "contractId":null,
         "status":"Scheduled"
      }
   ],
   "prerequisites":[ 
      { 
         "preq_id":"M12345",
         "preq_type":"FLAG",
         "preq_date_time":"2019-10-02T03:28:00Z",
         "preq_last_update":"2018-12-03T13:30:00Z",
         "preq_crew_id_id":"W_FOD_013",
         "wr_number":"4329502",
         "preq_crew":{ 
            "crew_id":"W_FOD_013",
            "crew_name":"Pre-req 1",
            "expertise":"Flush"
         },
         "facilities":[ 
            { 
               "facility_id":"VS1234",
               "facility_type":"VAULT",
               "facility_lat":40.758896,
               "facility_long":-73.98513,
               "facility_notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
            }
         ]
      }
   ],
   "workComponents":[ 
      { 
         "wc_number":"888-FOD-CO-950-609",
         "wc_type":"PSMECH",
         "wc_description":"Make halves, pick up VS1234.",
         "wc_crew_id":"W_FOD_013",
         "wc_start_date_time":null,
         "wc_end_date_time":null,
         "wc_estimated_hours":10.0,
         "wc_scheduled_start_date_time":"2020-02-16T19:23:02.866019Z",
         "wc_scheduled_end_date_time":"2020-02-17T19:23:02.866028Z",
         "wc_actual_hours":0.0,
         "wc_status":"Scheduled",
         "wc_notes":null,
         "wc_number_pre":"888-FOD-CO-178-0",
         "wc_number_post":"",
         "delay_type":null,
         "wr_number":"4329502",
         "wc_crew":{ 
            "crew_id":"W_FOD_013",
            "crew_name":"Pre-req 1",
            "expertise":"Flush"
         },
         "facilities":[ 
            { 
               "facility_id":"VS5678",
               "facility_type":"VAULT",
               "facility_lat":40.758896,
               "facility_long":-73.98513,
               "facility_notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
            }
         ]
      },
      { 
         "wc_number":"888-FOD-CO-178-0",
         "wc_type":"PSMECH",
         "wc_description":"Make halves, pick up VS1234.",
         "wc_crew_id":"W_FOD_013",
         "wc_start_date_time":"2019-12-02T04:28:00Z",
         "wc_end_date_time":"2019-12-03T13:30:00Z",
         "wc_estimated_hours":10.0,
         "wc_scheduled_start_date_time":null,
         "wc_scheduled_end_date_time":null,
         "wc_actual_hours":10.0,
         "wc_status":"Pending\n",
         "wc_notes":"We noticed that VS5678 may require additional maintenance soon.",
         "wc_number_pre":"",
         "wc_number_post":"",
         "delay_type":"",
         "wr_number":"4329502",
         "wc_crew":{ 
            "crew_id":"W_FOD_013",
            "crew_name":"Pre-req 1",
            "expertise":"Flush"
         },
         "facilities":[ 
            { 
               "facility_id":"VS1234",
               "facility_type":"VAULT",
               "facility_lat":40.758896,
               "facility_long":-73.98513,
               "facility_notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
            }
         ]
      }
   ]
} 

I have a JSON object containing arrays. I want to merge the facility arrays with the same facility id from Prerequisites and WorkComponents arrays, creating a new array that contains the facility id and preq_type with wc_type separate by comma if they share the same facility id. How can I achieve this using JavaScript? Thank you.

Expected Result :

[
        {
            "facility_id": "VS1234",
            "type": ["FLAG", "PSMECH"]
        }
]

Answer №1

To consolidate the data, you can utilize multiple forEach loops to construct a single object.

const data = {
  workRequestCompleted: [
    {
      number: "4329502",
      name: "Scheduled Outage Primary Feeder",
      startDate: "2019-07-01",
      endDate: "2019-07-10",
      lastUpdate: "2019-12-01T05:00:00Z",
      contractId: null,
      status: "Scheduled"
    }
  ],
  prerequisites: [
    {
      preq_id: "M12345",
      preq_type: "FLAG",
      preq_date_time: "2019-10-02T03:28:00Z",
      preq_last_update: "2018-12-03T13:30:00Z",
      preq_crew_id_id: "W_FOD_013",
      wr_number: "4329502",
      preq_crew: {
        crew_id: "W_FOD_013",
        crew_name: "Pre-req 1",
        expertise: "Flush"
      },
      facilities: [
        {
          facility_id: "VS1234",
          facility_type: "VAULT",
          facility_lat: 40.758896,
          facility_long: -73.98513,
          facility_notes:
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        }
      ]
    }
  ],
  workComponents: [
    {
      wc_number: "888-FOD-CO-950-609",
      wc_type: "PSMECH",
      wc_description: "Make halves, pick up VS1234.",
      wc_crew_id: "W_FOD_013",
      wc_start_date_time: null,
      wc_end_date_time: null,
      wc_estimated_hours: 10.0,
      wc_scheduled_start_date_time: "2020-02-16T19:23:02.866019Z",
      wc_scheduled_end_date_time: "2020-02-17T19:23:02.866028Z",
      wc_actual_hours: 0.0,
      wc_status: "Scheduled",
      wc_notes: null,
      wc_number_pre: "888-FOD-CO-178-0",
      wc_number_post: "",
      delay_type: null,
      wr_number: "4329502",
      wc_crew: {
        crew_id: "W_FOD_013",
        crew_name: "Pre-req 1",
        expertise: "Flush"
      },
      facilities: [
        {
          facility_id: "VS1234",
          facility_type: "VAULT",
          facility_lat: 40.758896,
          facility_long: -73.98513,
          facility_notes:
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        }
      ]
    },
    {
      wc_number: "888-FOD-CO-178-0",
      wc_type: "PSMECH",
      wc_description: "Make halves, pick up VS1234.",
      wc_crew_id: "W_FOD_013",
      wc_start_date_time: "2019-12-02T04:28:00Z",
      wc_end_date_time: "2019-12-03T13:30:00Z",
      wc_estimated_hours: 10.0,
      wc_scheduled_start_date_time: null,
      wc_scheduled_end_date_time: null,
      wc_actual_hours: 10.0,
      wc_status: "Pending\n",
      wc_notes:
        "We noticed that VS5678 may require additional maintenance soon.",
      wc_number_pre: "",
      wc_number_post: "",
      delay_type: "",
      wr_number: "4329502",
      wc_crew: {
        crew_id: "W_FOD_013",
        crew_name: "Pre-req 1",
        expertise: "Flush"
      },
      facilities: [
        {
          facility_id: "VS1234",
          facility_type: "VAULT",
          facility_lat: 40.758896,
          facility_long: -73.98513,
          facility_notes:
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        }
      ]
    }
  ]
};

const res = {};

data.prerequisites.forEach(pre => {
  pre.facilities.forEach(fac => {
    res[fac.facility_id] =
      fac.facility_id in res
        ? {
            ...res[fac.facility_id],
            type: [...res[fac.facility_id].type, pre.preq_type]
          }
        : { facility_id: fac.facility_id, type: [pre.preq_type] };
  });
});

data.workComponents.forEach(work => {
  work.facilities.forEach(fac => {
    res[fac.facility_id] =
      fac.facility_id in res
        ? {
            ...res[fac.facility_id],
            type: [...res[fac.facility_id].type, work.wc_type]
          }
        : { facility_id: fac.facility_id, type: [work.wc_type] };
  });
});

const required_data = Object.values(res);

console.log(required_data);

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

Developing a Javascript Function for Button Click Action and Verifying Input Fields

I am encountering significant difficulties with this issue. Despite my extensive search efforts, I am hoping that someone can offer assistance on either explaining the process or demonstrating it to me. Here is the challenge I am facing: Within an ASP.Net ...

What is the best way to run a script following the completion of an external asynchronous script within the header tag?

Utilizing Webflow's custom code editor, I incorporated an external script from Finsweet within the <head> tag as per their instructions. Although I would like to modify the page with my own script following the execution of Finsweet's scri ...

Troubleshooting: Issue with selecting items in jQuery Datatables

While attempting to construct a jQuery datatable using a data object, I encountered an issue. The table is displayed correctly, but the selection feature within the datatable is not functioning as intended. My expectation was that when a row is selected, i ...

Dealing with javascript onsubmit form problems

I am feeling really lost when it comes to incorporating JavaScript into my HTML code. I am attempting to validate a form either "onblur" or upon submission using an external file. Below is the HTML code that successfully works for the initial field: ...

Sending bulk SMS with Twilio using Node.js - A step-by-step guide

I am seeking guidance on how to send SMS notifications to multiple numbers using Twilio. I have a String Array with different phone numbers and would like to be able to send the same message to all of them. Here is an example of what I'm trying to ach ...

"Switching Classes with a Click Event: A Step-by-

This script is designed to work with SoundCloud's widget in order to enable remote text buttons. I am attempting to modify it so that it functions as a remote for an image button that toggles between different pictures for pause and play, rather than ...

Tips for styling the x-axis with date values in d3js

Thank you in advance! I am currently working on displaying data from a node module called google-finance. I have managed to draw a linear graph chart, but since I am new to d3, I am unsure of how to format and display the dates correctly. "date": "2 ...

Tips for showcasing array data on a single line with CDetailView

Here is the code snippet to be discussed: <?php $this->widget('zii.widgets.CDetailView', array( 'data'=>$model, 'attributes'=>array( 'tag', // problem here ), )); If there is an array wi ...

C++: separating text file content into multiple arrays based on delimiters

Good day everyone, First and foremost, I appreciate you dedicating your time to contribute and assist me in comprehending my issue. I must make it clear that this is an assignment problem, so I am seeking clarification rather than complete code. Regardin ...

What is the best way to find the maximum z-index value among multiple divs with the same name?

Similar Query: Select DIV with highest z-index Is there a way to retrieve the topmost z-index value? Should I store all div z-index values in an array and use math.max, or do you have any other suggestions? <div class="a" z-index="1"> <div ...

Guide on displaying a series of lists in OCaml

Hey there, I'm having trouble printing my list of lists. I've tried multiple methods but just can't seem to find a solution. I attempted to convert my list of lists into an array because I know how to print arrays. I used the function let s ...

Tips for removing negative duplicate values in an array

Is there a way to efficiently remove negative duplicates of positive integers from a mixed array of positive and negative integers, such as: [1, 5, 10, 5, -5, -1, 9] After the process, the desired output should be: [1, 5, 10, 5, 9] (To clarify, -1 and -5 ...

What is the best way to deliver hefty files to users? Utilize the node-telegram-bot-api

bot.sendDocument(id, 'test.zip'); I am facing an issue while trying to send a 1.5GB file using the code above. Instead of being delivered to the user, I receive the following error message: (Unhandled rejection Error: ETELEGRAM: 413 Request En ...

Creating a two-dimensional array within a function using malloc() to allocate memory

Currently facing an issue. I am trying to create a function that can allocate memory for a 2D array using malloc(), but I seem to be stuck and unable to identify what the problem might be. Here is the code I have written so far: void initializeMatrix(int ...

Guide to parsing a JSON array enclosed in square brackets within curly braces

I'm having trouble retrieving the array data within square brackets inside curly braces. The JSON output is as follows: {"data":{"user":[{"transaction":"45455","date":"2013-10-28" }],"msg":"ok"},"error":[]} I attempted the following: $obj = json_de ...

Resolving the 'Uncaught TypeError: number is not a function error' and tackling the 'Failed to load resource' issue

What is causing the error in the code? var images = ['/test/img/Gallery/large/4cba0c8a-4acc-4f4a-9d71-0a444afdf48d.jpg','/test/img/Gallery/large/4cba0ca8-2158-41af-829a-0a444afdf48d.jpg','/test/img/Gallery/large/4cbc549a-5228-433f ...

Preventing conflicts while toggling visibility with JQuery across various groups

My navigation system allows me to show/hide divs and toggle an 'active' class on the navigation items. However, I've encountered conflicts when trying to use similar sections on the same page (clicking a link in one section affects divs in o ...

In search of an effortless method to effortlessly select numerous elements using a handy bookmarklet

My goal is to develop a bookmarklet that can perform various functions on different webpages with ease. The concept involves placing it in a convenient location, such as the bookmark bar, and executing a "standard function" on a particular page. Instead of ...

"Error encountered: Module not found - Issue resolving module" while using signrequest-client in Angular

I've been attempting to integrate the signRequest API into my angular application. To do so, I first installed the signrequest-client using the following command: npm install signrequest-client --save Following this installation, I included the Ja ...

The styles order definition in the Material-UI production build may vary from that in development

When using material-ui, an issue arises in the production build where the generated styles differ from those in development. The order of the material-ui styles in production does not match the order in development. In DEV, the material-ui styles are defi ...