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

Incorporate text onto an image using Semantic UI

Currently, I am utilizing Semantic UI to display images. While it is functioning well for me in terms of adding text near the image, I desire to have the text positioned on top of the image. Ideally, I would like it to be located on the lower half of the i ...

Securing your folders with Next Auth middleware

I am currently developing a NextJS application and have implemented routers at pages/dashboard/* that I need to secure. My goal is to restrict access to these routes only to authenticated users. I am utilizing Prisma for data management, with Google as the ...

Is it possible to use both MUI makeStyles and Theming in the _app.js file?

I've been working on a complex navigation component using MUI Persistent Drawers within a React + Next.js setup. To achieve the desired content shrinking effect based on state changes, I ended up placing the entire navigation system inside the _app.js ...

When using child_process to run a Python script in Node.js, a promise may not resolve properly if the process exits before all

Currently, I am facing an issue while trying to execute sublist3r within a node app. The script runs successfully but only displays the banner before abruptly exiting after about 5 seconds. Typically, the script should interact with the web and take approx ...

Use the Arrow Keys to guide your way through the Page

I am looking to enhance user experience by allowing them to easily navigate through my webpage using the arrow keys on their keyboard. The goal is for users to be able to move from one section to the next in a seamless manner, unless they are focused on an ...

What is the best way to retrieve the "value" property of an <input> element in HTML?

Imagine there is an <input> element. When using jQuery to get the attributes of this element, I have written the following code: console.log($("#radio").attr("type")); console.log($("#radio").attr("value")); <script src="https://cdnjs.cloudflar ...

The decision will be dependent on the outcomes provided by the $resource promise

I have been working on calling my API with AngularJS to retrieve a list of 'reports' and then displaying them in a modal or saving the sale depending on whether any results were returned. I've been struggling with this for a while and would ...

Guide on generating a fresh array of objects that encompass distinct items, alongside their combined prices and quantities using JavaScript

I am struggling to generate a new array of objects from one that contains duplicates. For instance, here is the console.log output of the current array: console.log(items); [{ _id: 5eb2f7efb5b8fa62bcd7db94, workName: 'best item ever', ...

Is there a way to create an HTML select element where each option has a unique background color, and will display properly

I want to create multiple HTML select elements with unique background colors for each option: <select runat="server" id="select"> <option value="A">White</option> <option value="B">Red</option> <option value="C">Yellow& ...

Exploring ways to access elements within shadow-root (open) in Angular using SVG.js

I'm currently tackling a project involving Angular Elements. Within this specialized component, my goal is to incorporate SVG.js 3+. However, due to the necessity of utilizing ViewEncapsulation.ShadowDom in my component, I am encountering challenges w ...

Conceal rows in the table until the search (filterBy) is completed

Currently, I am utilizing Vue.js version 1.x and plan to update soon. My requirement is to have a table of rows containing some data. To filter the table rows using filterBy, I am using a Vue.js component. However, I want the table rows to remain hidden un ...

Receiving a segmentation fault when attempting to parse decimal numbers from a string in the C programming

#include <stdio.h> #include <stdlib.h> #include <string.h> int ExtractValues(char input[], double output[]) { int index = 0, i, j, length; i = 0; j = 0; length = 0; char substring[50]; while(i < strlen(input) - ...

Utilizing GroupBy in RxJs for an Observable of Objects数组

I am working with entries of type Observable<Event[]>, and they are structured as follows: [{ "_id": 1, "_title": "Test Event 1", "_startDate": "2019-05-29T07:20:00.000Z", "_endDate": "2019-05-29T08:00:00.000Z", "_isAllDay": false }, ...

Is there a method to redirect and display a JavaScript message efficiently?

Once the user has updated a record, I want to automatically redirect them to another page where they will be notified with a JavaScript message (alertify.notify()) confirming that the update was successful. I am unsure if it's possible to dynamically ...

What is the best way to utilize functions from different JavaScript files?

I'm currently handling server-side javascript and I've got confidential data that needs to remain secure, stored in a private directory. If I choose to enclose this data within a function, how can I go about invoking that function from a separate ...

Unexpected issue with Ionic 4 subarray returning as undefined even though the index is accurate

When attempting to use console.log to view the value, I noticed that the value of noticeSet2[index] is undefined. However, when I print noticeSet, all the data in the array is displayed. Additionally, after printing the index using console.log, it correctl ...

What is the best way to change the color of my Material Icons when I move my cursor over them?

Currently, I am integrating mui icons 5.2.0 into my React application. Although the icon appears on the page, it remains unchanged in color when I try to hover over it. Check out the snippet of code that I have implemented: import EditIcon from '@mu ...

Incorporating a new dropdown menu above the content of a pre-existing jQuery accordion dropdown, causing the content to shift downwards

Seeking a way to overlay a second-level dropdown menu on top of the content beneath a jQuery accordion-style dropdown. Typically, the jQuery accordion pushes down the content below, but I want the second-level dropdown to remain unaffected. Is there a solu ...

Tips for avoiding Google Tag Manager from interfering with document.write() function

We have integrated Angular into our website, however, not all pages have been migrated to Angular yet. To handle this situation, we have implemented a hybrid approach: Each request is initially directed to Angular. Once the page is loaded, it checks if th ...

Tips for obtaining the correct Javascript output for the number pyramid

I'm currently in the process of creating a half pyramid of numbers, but I'm facing an issue with getting the output to show the total for each line while maintaining everything except the * sign between the numbers. If anyone is able to offer som ...