Can normalizr be used to normalize JSON data that is similar to Excel spreadsheets but does not contain IDs?

Is there a way to restructure the following JSON data into a more organized format?

{
"rows": [{
        "cells": [{
                "value": "Column Name 1"
            },
            {
                "value": "Column Name 2"
            },
            {
                "value": "Column Name 3"
            },
            {
                "value": "Column Name 4"
            }
        ]
    },
    {
        "cells": [{
                "value": "Second Row Thing1"
            },
            {
                "value": "Second Row Thing2"
            },
            {
                "value": "Second Row Thing3"
            },
            {
                "value": "Second Row Thing4"
            }
        ]
    },
    {
        "cells": [{
                "value": "Third Row Thing1"
            },
            {
                "value": "Third Row Thing2"
            },
            {
                "value": "Third Row Thing3"
            },
            {
                "value": "Third Row Thing4"
            }
        ]
    }
]

}

I would like to transform it into the following format:

{
    "rows": [{
            "Column Name 1": "Second Row Thing1",
            "Column Name 2": "Second Row Thing1",
            "Column Name 3": "Second Row Thing1",
            "Column Name 4": "Second Row Thing1"
        },
        {
            "Column Name 1": "Third Row Thing1",
            "Column Name 2": "Third Row Thing1",
            "Column Name 3": "Third Row Thing1",
            "Column Name 4": "Third Row Thing1"
        }

    ]
}

Would "normalizr" be able to achieve this restructuring, or should I explore using methods like "map", "foreach", and other array functions?

Answer №1

Using Normalizr is not necessary in this case (and actually counterproductive since it will not yield the desired result). Normalizr is designed for handling nested data structures, such as entities with references to other entities (e.g., users embedded within tweets).

For a task like this, Map/Reduce can be highly effective. Below is a code snippet that accomplishes what you are looking for.

const data = { "rows": [
  { "cells": [{ "value": "Column Name 1" }, { "value": "Column Name 2" }, { "value": "Column Name 3" }, { "value": "Column Name 4" } ]},
  { "cells": [{ "value": "Second Row Thing1" }, { "value": "Second Row Thing2" }, { "value": "Second Row Thing3" }, { "value": "Second Row Thing4" } ] },
  { "cells": [{ "value": "Third Row Thing1" }, { "value": "Third Row Thing2" }, { "value": "Third Row Thing3" }, { "value": "Third Row Thing4" } ] }
}};

// Extracting column names
const columns = data.rows[0].cells.map(({ value }) => value);

// Processing each row of cells
const normalizedData = data.rows.slice(1).map(({ cells }) => {
  // Converting array of cells into an object map
  return cells.reduce((memo, { value }, i) => {
    memo[columns[i]] = value;
    return memo;
  }, {});
});

console.log(JSON.stringify(normalizedData, null, 2));

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

What is the method to receive a JSON response from an HTTPRequest without relying on templates?

I am fairly new to using Django, although I consider myself an experienced programmer in other frameworks. My Goal: To press a form button that triggers Javascript to initiate an Ajax request. This request will be handled by a Django View which will crea ...

After clicking multiple times within the modal, the modal popup begins to shift towards the left side

I successfully implemented a modal popup in my project, but encountered an issue where the popup moves to the left side if clicked multiple times. Despite searching extensively online, I have not been able to find a solution to this problem. Below is the ...

Managing shared states across different components in React

After coming across articles that criticize React for its setState functionality, I have realized that some critics may not fully comprehend it. Despite this criticism, I personally appreciate the modularity of React and find it more intuitive as I delve d ...

The placement of the FirebaseAuth.onAuthStateChanged call in an Angular application is a common concern for developers

Where is the best place to add a global listener initialization call in an Angular app? Take a look at this code snippet: export class AuthService { constructor( private store: Store<fromAuth.State>, private afAuth: AngularFireAuth ) { ...

What is the best way to interpret a nested JSON object?

Recently I've crafted an object that looks like this. myObj = { "name":"John", "age":30, "cars": [ "car1":"Ford", "car2":"BMW", "car3":"Fiat" ] } While it's pretty straightforward to read the name and age properties, I find ...

Save JSON files within Hyperledger Fabric

I am looking to implement a private blockchain system that can efficiently store complex data structures like JSON documents. The concept is to have each transaction represented as a JSON document, potentially with different schemas. After researching, i ...

Using various hues for segmented lines on ChartJS

I am working with a time line chart type and I want to assign colors to each step between two dots based on the values in my dataset object. In my dataset data array, I have added a third item that will determine the color (if < 30 ==> green / >3 ...

Error: JSON array contains unterminated string literal

Hey there, var favorites = 'Array ( [0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "] [1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "] [2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "] ) '; I've been encountering a syntax error - an untermi ...

"Exploring the World of Angular and Vue: Harnessing the Power

As a beginner developer, I've been busy familiarizing myself with Angular, React, and Vue. It seems like each of these frameworks use "declarative binding" and "templating". While I grasp the concept of what these are, I'm struggling to see why t ...

Current polyfill available for requestAnimationFrame

Recently, I read on that requestAnimationFrame in Chrome 20 now has a new sub-millisecond precision timer. It looks like I need to update my code to accommodate this change. After checking out various polyfills, it seems like they were created before thi ...

Using Express.js to transform req.body into a POST encoded string

I need to convert the req.body object into a POST encoded string using the express.bodyParser middleware. Is there a way to achieve this? For example: Name: Jane Doe Age: 30 City: Los Angeles Should become: Name=Jane+Doe&Age=30&City=Los+Angeles ...

Tips for transferring data from a nested component's state to its parent component

I am facing a challenge in extracting the state value from one component to another when clicking on a tag. The goal is to append the value of the clicked tag to a list state in the Form component. Can someone suggest a simple approach to achieve this? T ...

There seems to be a problem with completing the Axios post request in the Javascript Front

My front-end, built with React, is having trouble retrieving data from a third-party API through my Node.js backend. Despite using axios.post request, the response remains undefined and I'm stuck at handling the asynchronous request. It appears that t ...

Tips on sorting objects by comparing them to array elements

I have an array called myarrays and an object named obj. I need to filter the object by comparing the elements of the array with the keys of the object. If you want to see the code in action, you can check it out on StackBlitz: https://stackblitz.com/edit ...

Error in browser caused by JQuery JavaScript, not Dreamweaver

I need help creating a webpage that can extract and display recent earthquake data based on user input location on Google Maps. I have been using Dreamweaver to test my code, and everything functions perfectly when I use the live webpage feature within th ...

What is the right time to use parentheses when calling functions - and when should you leave them

Currently, I am following along with a tutorial at this link and I've come across some syntax that is confusing to me. The goal is to have "hello" logged to the console every time I scroll. function moveCamera() { console.log("hello"); } document. ...

What is the best way to display an image and text side by side within a single row in react-table?

I am trying to display an image and text side by side within a single column in a React table. I have successfully added two texts together in a single column using the code below: Header: "Name", id: "User", accessor: (d) => ...

Issue with sending JSON data in POST request using sails.js

I encountered an error with the body-parser while attempting to POST a basic json body to my controller using fetch. 1] error: Unable to parse HTTP body- error occurred :: 'SyntaxError: `Unexpected token -\n at parse (/project/node_modul ...

The React Stripe API is functioning perfectly on local servers but encountering issues in the live environment

Just when I thought I was almost finished, reality hits me hard! My deadline is right around the corner! I finally got everything working on my local machine with a stripe payment form. However, when I pushed it live, I received an error message from my A ...

The JavaScript function for clearing an asp.net textbox is not functioning properly

I am working on an ASP.net project and have encountered an issue with two textboxes. When one textbox is clicked on, I want the other one to clear. Below is the code I have for the textboxes: <asp:TextBox runat="server" ID="box1" onfocus="clearBox2()" ...