Break down objects into arrays of objects in JavaScript

Hello, I'm struggling with transforming this object into an array of objects.

The 'number' and 'reason' fields are currently stored as strings separated by commas. I need to split them into their own separate objects. The example dataset along with the desired output is shown in the code snippet below.

// Initial data structure
const data = {
  date: "2021-09-07 10:28:34,2021-09-08 14:45:22",
  startDate: "2021-09-07 00:00:00,2021-09-08 14:45:22"
  id: "111111"
  number: "1,9"
  reason: "Autres,Autres"

}

// Expected output:
const res = [{
    date: "2021-09-07 10:28:34",
    startDate: "2021-09-07 00:00:00",
    id: 11111,
    number: 1,
    reason: "Autres"
  } {
    date: "2021-09-08 14:45:22",
    startDate: "2021-09-08 14:45:22",
    id: 11111,
    number: 9,
    reason: "Autres"
  }]

Answer №1

  1. Convert the original object with string-combined-columns into an object with columns split as arrays by using the reduce method and spread operator.

    1a. Identify column names from the original object by excluding the 'id' column.

    1b. Keep track of the number of rows during the projection process.

  2. Go through each row based on the row count obtained above, creating a new object for each row and extracting relevant column values using the current iteration index.

    const original = {
      date: "2021-09-07 10:28:34,2021-09-08 14:45:22",
      startDate: "2021-09-07 00:00:00,2021-09-08 14:45:22",
      id: "111111",
      number: "1,9",
      reason: "Autres,Autres"
    };
    
    function split(obj) {
      const columnNames = Object.keys(obj).filter(key => key !== "id");
      const singleWithSplitted = columnNames.reduce((result, columnName) => {
        const splittedArray = obj[columnName].split(",");
        return ({
          rowsCount: Math.max(result.rowsCount, splittedArray.length),
          table: { ...result.table,
            [columnName]: splittedArray
          }
        });
      }, {
        rowsCount: 0
      });
      const arr = [];
      for (i = 0; i < singleWithSplitted.rowsCount; i++) {
        const result = {
          id: obj.id
        };
        columnNames.forEach((columnName) => {
          result[columnName] = singleWithSplitted.table[columnName][i];
        });
        arr.push(result);
      };
      return arr;
    }
    console.log(split(original));

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

Avoiding type errors in d3 v5 axis by using Typescript

I am new to TypeScript and I have some code that is functioning perfectly. I believe if I define a type somewhere, d3's generics will come into play? Within my code, I have an xAxis and a yAxis. Both are the same, but D3 seems to have an issue with t ...

Populate an array with information retrieved from a database

Currently, I am working on a script to search for specific data and populate it into a graph that I have already created. The goal is to display a list of the data present in a particular section of the graph when hovered over. For instance: If 25% of ...

Google Chrome is unable to process Jquery JSON .each() function

My website has a simple chat application that is functioning well. It uses ajax to request data in this manner: $.ajax({ url: "fetch/"+CHAT_SESSION_ID+"/"+LAST_MESSAGE_ID, dataType: "json", cache: false, success: function(data) { if (data.session_ac ...

Looking for assistance with updating a JavaScript Object Array and embedding it into a function

Below is the code snippet I am working with: $("#map4").gMap({ markers: [ { address: "Tettnang, Germany", html: "The place I live" }, { address: "Langenargen, German ...

Retrieve pixel information upon touch in an Appcelerator Titanium application on Android or iPhone

Can pixel level data of an image view be accessed using Titanium Mobile on Android/iPhone? ...

Creating an associative array in javascript: A step-by-step guide

I require an array to be structured in the following manner: {"3": {"label":"All i want for christmas", "song":"Alliw_1405399165.mp3", "name":"All i want for christmas"}, "4": {"label":"Call your girlfriend robyn clip", "song":"Gang ...

Verifying if the completion of the busboy event has already happened or not

In the form I have, there is a file processing task that takes some time to complete. Currently, while node is processing the files, if it encounters the finish event, it immediately triggers it. How can I ensure that the finish event is only fired after a ...

Substitute the specific class title with the present class

Here is a sample class (supposed to be immutable): class A { normalMethod1(): A{ const instance = this.staticMethod1(); return instance; } static staticMethod1: A(){ return new this(); } } The code above works fine, but how can I re ...

How to Access a div from another website using jQuery

I have a question. How can I call a div from another website using JavaScript? Here is the page: Now, I want to call the <div id="testa"> in another page. The other page is called Otherpage.html: jQuery(function($){ $(&ap ...

How to set up 'ng serve' command in Angular to automatically open a private browsing window?

I am looking for a way to open my project in an Incognito Mode browser without storing any cache. Is there a specific Angular CLI flag that can be included in the ng serve -o command or in the Angular CLI configuration file to enable opening a browser in ...

Is it possible to modify the express static directory path depending on the route being accessed?

I am trying to dynamically change the static path based on the route. Here is an example of what I have tried: const app = express(); const appRouter = express.Router(); const adminRouter = express.Router(); appRouter.use(express.static('/path/to/ap ...

Adding arrays to a larger array

<?php $images =[]; $imagesArrays = []; //Querying the database for image galleries $loop = new WP_Query( array( 'post_type' => 'gallery', 'posts_per_page' => 100 ) ); while ( $loop->have_po ...

Unveiling the Mystery: How Browser Thwarts Server Push in HTTP/2.0

After studying the documentation of HTTP/2.0, I discovered that it is feasible to completely close a referenced stream using the RST_STREAM frame. Check it out here: ()! I am curious about how this feature can be implemented in popular web browsers such a ...

I'm having trouble with my dataTable creation using JQuery. Can anyone help me troubleshoot?

I've attempted various methods to make this work. Here's what I'm importing: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <script type="text/javascript" src="https://cdn.datatabl ...

The Discord OAuth2 bot fails to assign roles to authenticated users

While working on OAuth2 login for my website, I encountered an issue. After a user successfully logs in through OAuth2, the bot should assign a role to them on my Discord server. However, when I tested the login process myself, the bot returned an error me ...

Has xlink:href become outdated for svg <image> elements?

In the realm of SVG attributes, it is noted by MDN xlink:href that href should be used over xlink:href. Interestingly, on the svg example page, last revised on July 6, 2017, the attribute utilized in the given example is xlink:href. The question arises: ...

Open a fresh window using Javascript and add new content inside

After creating a script that opens a window and writes content when the button is clicked once, I noticed that clicking the button again causes the window to gain focus instead of rewriting the content. Does anyone have any ideas on how to fix this issue ...

What kind of data structure is suitable for a MediaStream when passing it as a prop in a Vue component

Currently, I have set up a mediastream (multi WebRTC) and plan on placing each MediaStream into the child component that contains a video tag. The stream type is MediaStream, however there is no corresponding type for a Vue prop. Refer to the Vue documenta ...

Leaflet setStyle changes are effective when applied through the console but do not reflect in the actual

I currently have a map with around 1000 polygons that I am loading onto it. My goal is to color these polygons based on a specific property value. The code snippet below showcases my approach, but the results are not as expected. mapLayerFieldGrid = new L ...

Why does the CLI crash when attempting to retrieve all data from an Oracle Database with JQuery?

Trying to utilize JavaScript and Jquery for database search, a generic query.php file has been set up to pass in the database and query, returning an array. Strangely, when attempting to select all using *, the PHP server crashes with: https://i.stack.img ...