transform an object into an array of objects

After receiving data from the backend, it looks like this:

 const fetchResult = { 
            cmo: 'integrated', 
            schedule1: '2021-08-12', 
            schedule2: '2021-09-20', 
            kendaraan: {}, 
            kubikasi1: 207000, 
            kubikasi2: 20000,
            status_so1: true,
            status_so2: false,
}

My desired format is as follows:

const result = [
  {
    schedule: value,
    kubikasi: value,
    status_so: true
  },
  {
    schedule: value,
    kubikasi: value,
    status_so: false
  },
]

I aim to convert the JSON data received from the backend into an array of objects and group it according to the expected format. The dynamic nature of data elements like schedule from the API should be considered.

Here's what I have attempted so far:

for (let i = 1; i <= 4; i++) {
        if (cmo["schedule_" + i]) {
          data.push({
            schedule: cmo["schedule_" + i],
            namakendaraan: cmo["namakendaraan" + i],
            kendaraan: cmo["kendaraan" + i],
            totalCarton: cmo["totalCarton" + i],
            tonase: cmo["tonase_" + i],
            totalTonaseKendaraan: cmo["totalTonaseKendaraan" + i],
            totalPercentaseTonaseOrder: cmo["totalPercentaseTonaseOrder" + i],
            kubikasi: cmo["kubikasi_" + i],
            totalKubikasiKendaraan: cmo["totalKubikasiKendaraan" + i],
            totalPercentaseKubikasiOrder:
              cmo["totalPercentaseKubikasiOrder" + i],
            nomor_so: cmo["nomor_so_" + i],
            status_so: cmo["status_so_" + i],
          });
        } else {
          data.push({
            schedule: null,
            namakendaraan: null,
            kendaraan: null,
            totalCarton: null,
            tonase: null,
            totalTonaseKendaraan: null,
            totalPercentaseTonaseOrder: null,
            kubikasi: null,
            totalKubikasiKendaraan: null,
            totalPercentaseKubikasiOrder: null,
            nomor_so: null,
            status_so: null,
          });
        }

Answer №1

To streamline the object's data, convert it into a Map. Iterate through each entry and extract the key along with the number (idx). If no number is present, move on to the next iteration by returning the accumulator (which is the Map). In case the idx exists, update or add the object in the Map:

const fetchData = {"product":"phone","price":500,"color":"black"}

const newData = Array.from(Object.entries(fetchData)
  .reduce((acc, [k, v]) => {
    const [key, idx = null] = k.split(/([0-9]+$)/)
    
    return idx === null
      ? acc
      : acc.set(idx, { ...acc.get(idx), [key]: v })
  }, new Map()).values())
  
console.log(newData)

Answer №2

Organize the entries of the object based on numbers, condense them into nested arrays, and then transform them into an array of objects.

const inputObject = { country1: 'USA', country2: 'Canada', population1: 300000000, population2: 37000000 }

const result = Object.entries(inputObject).reduce((acc, curr) => {
    if (parseInt(curr[0][curr[0].length - 1]) > 0) {
        const index = parseInt(curr[0][curr[0].length - 1]) - 1
        const pair = [curr[0].substring(0, curr[0].length - 1), curr[1]]
        !acc[index] ? (acc[index] = [], acc[index].push(pair)) : acc[index].push(pair)
    }
    return acc
}, []).map(item => Object(Object.fromEntries(item)))

console.log(result)

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

Checking the boxes in javascript

Hey there, I'm a JavaScript newbie and struggling to validate my check-boxes. Despite looking at multiple examples, the concept is still not sinking in for me. Could someone please provide guidance on how to properly validate my check-boxes? Additiona ...

Retrieving JavaScript return values in a C# WebBrowser control within a WPF application

I utilized JavaScript injection into WebBrowser control in C# (System.Windows.Controls.WebBrowser) to achieve, <C#> IHTMLDocument2 webdoc = (IHTMLDocument2)webBrowser1.Document; string var = File.ReadAllText("C:/.../Resources/script.txt"); object re ...

ZeroMQ and Electron integration: Unable to find the specified bindings file

Currently, I am running Windows 7 x64 with nodejs 5.1.0 and Electron 0.35. I carefully followed the instructions provided by the Electron Quick Start app and then proceeded to add the line require("zmq") to the main.js file. However, upon executing npm ins ...

Displaying data from a table in a modal window using getSelected in Bootstrap-table

I am currently utilizing bootstrap and bootstrap-table, and I have a requirement to display the data of the selected item in a modal window. When I retrieve the information of the selected item: Here is my JavaScript code: var $table = $('#tableprod ...

Tips for successfully passing a variable as props within the confines of a different function's component

Is there a way to pass the variable id to the onConfirm event in this code snippet? Currently, it seems like the function is being called by another function within setAlert. How can I achieve this? const confirmationPrompt = (id) => { setAlert( ...

Exploring JavaScript through the Lens of Object-Oriented Concepts from Java

Having spent a significant amount of time using Java, I delved into web development with GWT (Google Web Toolkit) where the convenience of having my Java object-oriented constructs translated to GWT seamlessly by Google was a major draw. While my knowledge ...

Watch the video and follow along with your mouse using jQuery

Wouldn't it be cool to have a video play and follow your mouse pointer when you hover over the red box? And then once you move away, the video stops and disappears. Check out my progress so far: jsfiddle Here's the jQuery code I've used: $ ...

Guide on transforming an array containing indexed objects into a simple object

Can anyone help me with converting an array of this specific type? place: [ { "_id": "xxxxx", "loc": [ 0: "xxx", 1: "xxx" ] } ] Into something ...

Add CSS styles to the outermost container element when the slideshow is currently in use

On my homepage, I have a carousel featuring multiple slides. However, when the third slide appears in the carousel, the positioning of the carousel buttons within the div class="rotator-controls" shifts downward due to the space taken up by the image. My o ...

The graph from Flot is not showing up, and there are no error messages

Recently, I have been experimenting with creating a graph plot using flot. However, I've encountered an issue where the graph is not displaying as expected. Despite using developer tools and JSlint to check for errors in my JavaScript code, both tools ...

web browser freezing when trying to open bigger files

I have a project where I need to download multiple JSON data files and visualize them using D3 data charts. However, when the page loads, it takes around 2-3 minutes to download and visualize the files, especially on mobile devices. This causes the browser ...

Using AJAX to communicate with a MySQL database and create a countdown timer using JavaScript

I have been trying to display data from a database using Ajax and incorporate countdown timers with times also fetched from the same database. It has been a struggle for me for almost 24 hours now. You can check out the main code here where you will notic ...

Retrieve the text content from the HTML document

I'm facing a beginner's challenge. I have a div element and I want to extract the URL from the data-element attribute into a .json file Is there a way to do this? <div content="" id="preview" data-element="http://thereislink" class="sample ...

Using Regex with JavaScript while ignoring letter case

I am trying to extract a query string from my URL using JavaScript, and I need to perform a case-insensitive comparison for the query string name. In order to achieve this, here is the code snippet that I am currently using: var results = new RegExp(&apos ...

Highcharts-ng allows us to create charts without using the traditional syntax such as $('#container').high

After setting up the chart's configuration in my controller, I am facing an issue. The HighCharts-ng (an angularJS directive for HighCharts) has a method that I want to implement: $scope.ohlcChartConfig = { options: {....... I ne ...

Is it possible to simultaneously run watchify and node-sass watch together?

Currently, I am utilizing npm scripts in conjunction with watchify and node-sass while incorporating the -w parameter. I am curious if it is feasible to execute both of these 'watch' commands simultaneously. Would this setup ensure that only sty ...

Fetch information from DataObject's CSV file using JavaScript

After reading a csv file with the following code: var x="dema.csv"; loadCSV(x); function loadCSV(file) { if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari var request = new XMLHttpRequest(); } else { // ...

Assistance required in designing a unique shape using Three.js

https://i.sstatic.net/pmHP2.png Hello there! I could use some assistance with replicating the 2D shape shown in the image above using three.js. Specifically, I'm encountering some difficulty with incorporating the subtle curvature seen on the inner l ...

The issue lies with the Cookies.get function, as the Typescript narrowing feature does not

Struggling with types in TypeScript while trying to parse a cookie item using js-cookie: // the item 'number' contains a javascript number (ex:5) let n:number if(typeof Cookies.get('number')!== 'undefined'){ n = JSON.pars ...

What is the reason for object destructuring not functioning properly in styles?

Why is it that the HTMLelement is considered an object, while the style is also an object, yet this code fails to work as expected? When I remove destructuring, everything functions properly, so I am curious to understand the underlying reason behind thi ...