Organize data that is deeply nested

Struggling to normalize deeply nested API response data? Look no further than https://github.com/paularmstrong/normalizr. This tool can help simplify your data structure.

For example, if your input data looks like this:

const data = [{
  id: 'component1',
  name: 'component one',
  properties:[{
    name: 'text',
    color: 'red'
  }]
},
{
  id: 'component2',
  name: 'component two',
  properties:[{
    name: 'text',
    color: 'yellow'
  },{
    name: 'button',
    color: 'blue'
  }]
}]

The expected output after normalization should be:

    { 
      entities: {
        component1: {
           id: 'component1',
           name: 'component one',
           properties: {
             entities: {
               text: {
                  name: 'text',
                  color: 'red'
               }
             },
             results: ['text']
           }
        },
        component2: {
           id: 'component2',
           name: 'component two',
           properties: {
             entities: {
               text: {
                  name: 'text',
                  color: 'yellow'
               },
               button: {
                 name: 'button',
                 color: 'blue'
               }
             },
             results: ['text', 'button']
           }
        }
      },
      results: ['component1', 'component2']
    }

If you need any assistance, don't hesitate to ask for help.

Answer №1

In order to achieve the desired format, the approach I took was to iterate through all the data using the forEach() function:

const elements = [{id: 'item1',name: 'item one',properties:[{name: 'text',color: 'red'}]},{id: 'item2',name: 'item two',properties:[{name: 'text',color: 'yellow'},{name: 'button',color: 'blue'}]}];

let output = {entities: {}, result: []};
elements.forEach(el => {
  output.result.push(el.id);
  output.entities[el.id] = {
    id: el.id,
    name: el.name,
    properties: {
      entities: Object.fromEntries(el.properties.map(prop => [prop.name, prop])),
      results: el.properties.map(prop => prop.name)
    }
  };
});

console.log(output);

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

Transmitting JSON data from Stream Analytics to Power BI

https://i.sstatic.net/8gfqD.pngI'm currently working on sending simulated data from kepware to Azure Hub and then to Stream Analytics. The next step would be to send it directly to Power Bi, but it seems like stream analytics is sending an array to Po ...

Having trouble connecting to service while parsing JSON on Android

Currently, I am working on developing a method to call a service and retrieve JSON data in an Android application. All necessary global variables have been declared beforehand... The following libraries are being utilized: import java.io.BufferedReader; ...

Retrieving the chosen value when there is a change in the select tag

Building a shop and almost done, but struggling with allowing customers to change product quantities in the cart and update prices dynamically. I've created a select-tag with 10 options for choosing quantities. I'd like users to be able to click ...

Retrieving data from a collection based on a specific property or key in PowerShell

After successfully retrieving JSON data from a file using the code below: $jsonContent = (Get-Content $fullFilePath -Raw) | ConvertFrom-Json This is how the JSON content looks: { "Name" : "Fred", "Age" : 10 } I want to iterate through this data ...

Top 5 Benefits of Utilizing Props over Directly Accessing Parent Data in Vue

When working with VueJS, I've noticed different approaches to accessing parent properties from a component. For example, let's say I need to utilize the parent property items in my component. Option One In this method, the component has a props ...

Extracting user login details from a Java script-based web browser for a RASA chatbot

Our website integrates a web bot using Javascript. When users log in, they can access the chatbot icon. Currently, the chatbot starts without collecting user data. However, having user data is important as we plan to trigger actions based on user ID. If ...

Using Symfony 3 to iterate through an array containing different Classes

Is there a way to extract values from JSON data that have been placed into my classes (Match, Player)? I attempted using a foreach loop, but found it challenging since the data is stored in classes. Can someone provide guidance on how to tackle this issue ...

JSON: Automatically choose the radio button based on the provided response

Is there a way to automatically select the checked state of radio buttons based on data retrieved from a database? I need to populate this form's radio button with data <div class="col-md-4"> <label> <input type="radio" name="m ...

Using Express Router to serve and display static files in the public directory

The code snippet below is found in my index.js file: var express = require('express'); var app = express(); var PORT = 3000; var routes = require('./scripts/routes/routes'); app.set('views', './views'); app ...

Creating a mesmerizing glass effect in Three.js using a PNG image mask on a video texture

The other day, I revisited activetheory.net and was captivated by the beautiful glass effect on the Homescreen logo border. I tried to replicate it by examining the minified code and discovered they were using a PNG as a mask. I successfully loaded a PNG ...

Incorporate a distinct, unique value from a JSON dataset into each iteration of the .each statement

My code includes an each statement that looks like this: $.each(data, function(i, value) { sublayers.push({ sql: "SELECT " + firstSel2 + ", cartodb_id, the_geom_webmercator FROM full_data_for_testing_deid_2 where " + firstSel2 + "=&ap ...

It is not feasible to document JSON within a URL

For my Rest API, I am working on enabling the retrieval of data within a specific bounding box. Since the bounding box requires four coordinates, I intend to structure the GET requests in a way that allows them to accept the bounding box as JSON. This mean ...

Who needs a proper naming convention when things are working just fine? What's the point of conventions if they don't improve functionality?

I am a newcomer to the world of JavaScript programming and stumbled upon this example while practicing. <html> <head> <script type="text/javascript"> function changeTabIndex() { document.getElementById('1').tabIndex="3" d ...

The Angular $http.jsonp() function can only be executed one time

Upon the first response being successful (alert->done), any subsequent hits will result in an 'error' response. I attempted to resolve this issue by adding some config parameters with 'cache: false', but it still only works the firs ...

What is the best way to append data to the end of an object using ReactJS Hooks?

Looking to set up a checkbox page in ReactJS where data is filtered by checkboxes from different categories using ReactJS hooks. Currently, I am storing the selected checkboxes as an object: { color: 'orange', shape: 'square' } ...

Is it possible to use file upload for sending via Ajax's POST method?

Let's talk about the scenario at hand Here's what happens in a single form: 1) The user clicks on the 'browse' button, which opens a dialog to select an image file for uploading. Example: input id='img_upload' name="ufile" ...

Unable to communicate with MediaWiki API using jQuery

My attempt to retrieve content from Wikipedia in JSON format has been unsuccessful: $.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json", function(data) { doSomethingWith ...

What are the best practices for utilizing the "this" keyword with fetch?

After extensively studying ES6 documentation and the changes it brings, I am eager to incorporate the new oop syntax along with modern libraries such as fetch. Below is the code snippet I have been working on: apiCall(url, thisAlias=this){ fetch(url). ...

Issue with rendering components list in React.js

I am currently working on a project using React, and I'm facing an issue where my list is not displaying on render(). In my parent component, I have a list of components coming from SearchResult. Below is the relevant portion of my code: class Create ...

Is it possible in Angular.js to limit the visibility of a service to only one module or to a specific group of modules?

When working with Angular.js, the services declared on a module are typically accessible to all other modules. However, is there a way to restrict the visibility of a service to only one specific module or a selected group of modules? I have some service ...