Steps for converting JSON into a structured indexed array

My goal is to efficiently convert the data retrieved from my firebase database into a format suitable for use with a SectionList.

I have successfully established a part of the data structure, but I am facing challenges in associating the data correctly.

The required format for the SectionList is as follows:

[
         {
           index: 0,
           title: "Pan simple",
           data: [
             {
               id: 0,
             },  
             {
               id: 1,
             } 
           ]
         },
         {
           index: 1,
           title: "Pan dulce",
           data: [
             {
               id: 0,
             }

           ]
       }
   ]

The current format of the data received from my database is as shown below:

"storeName": { 
     products: { 
         '-Lo7D2Y8ZVEXnJb5LMvd': { 
             name: 'Pan de molde',
             category: 'Molde' 
         },
         '-Lo7C4HAkeE0cssxg9E-': { 
             name: 'Bollo de Hamburguresa',
             category: 'Hamburguesa' 
         } 
     },
     category: { 
         Molde: { 
             '-Lo7D2Y8ZVEXnJb5LMvd': true 
         },
         Hamburguesa: { 
             '-Lo7C4HAkeE0cssxg9E-': true 
         } 
      } 
  }

In this structure, the "title" corresponds to the keys within the categories and the "data" refers to the objects under the products branch. I have implemented a function to fetch and transform this data:

   export default (props, storeName) => {
      firebase
        .database()
        .ref(`Store/${storeName}`)
        .on("value", function(snapshot) {
          if (snapshot.val() != null) {
            var values = snapshot.val() || {};
            var dataFormat = [];
            var x = 0;
            for (var i in values.category) {
              var data = Object.assign({
                data: [],
                index: x,
                category: i
              });
              dataFormat.push(data);
              x++;
}
        console.log("Data", dataFormat);
      }
    });
};

Currently, the output is

[ 
    { data: [], index: 0, category: 'Molde' },
    { data: [], index: 1, category: 'Hamburguesa' } 
]

However, the desired output should be:

[ 
  { 
    data: [
      {
       id: 'Lo7D2Y8ZVEXnJb5LMvd', 
       name: 'Pan de molde',
       category: 'Molde' 
      }
    ], 
    index: 0, 
    category: 'Molde' 
  },
  { 
    data: [
      { 
        id: '-Lo7C4HAkeE0cssxg9E-',
        name: 'Bollo de Hamburguresa',
        category: 'Hamburguesa' 
      }
    ], 
    index: 1, 
    category: 'Hamburguesa' 
  } 
]

How can I ensure that the appropriate data is assigned to each section?

Answer №1

Quick notes:

  • No need for
    var values = snapshot.val() || {};
    since you already check if snapshot.val() is not null
  • Using an object literal with Object.assign is redundant; stick to the literal
  • You're in ES6 territory, so ditch var
  • A map would be more elegant than a for loop
  • The provided input lacks product IDs, so I left that out here; feel free to update the question for further details.

Here's my revised version based on your code snippet:

export default (props, storeName) => {
  firebase
    .database()
    .ref(`Store/${storeName}`)
    .on("value", function(snapshot) {
      const values = snapshot.val();
      if (values) {
        const dataFormat = Object.keys(values.category)
          .map((category, index) => ({
            category,
            index,
            data: Object.values(values.products).filter(
              product => product.category === category
            )
          }));
        console.log("Data", dataFormat);
      }
    });
};

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

Elegant bespoke input box

I am looking to create a customized input text feature similar to StackOverflow's tag editor, but with some minor differences. The goal is for the input field to function like a regular text input until a word is enclosed in curly brackets. Once enclo ...

Exploring Apache Nifi: Extracting JSON data from an API

As a novice Apache Nifi user, I am diving into the world of APIs and Elasticsearch integration. While I have successfully utilized the getTwitter and putElasticsearch controllers to manage JSON documents from Twitter, I am now facing a challenge when worki ...

Leveraging Angular to retrieve images from Google Feed API

I'm currently working on developing an RSS reader and trying to integrate images from the Google Feed API. While I have successfully extracted the publishedDate and contentSnippet, I am facing difficulty in getting the image src. The code snippets bel ...

Tips on setting a singular optional parameter value while invoking a function

Here is a sample function definition: function myFunc( id: string, optionalParamOne?: number, optionalParamTwo?: string ) { console.log(optionalParamTwo); } If I want to call this function and only provide the id and optionalParamTwo, without need ...

Raspberry Pi encountering a TypeError with Node.js async parallel: "task is not a function" error

I am new to nodejs, so I kindly ask for your understanding if my questions seem simple. I am attempting to use nodejs on a Raspberry Pi 3 to control two motors, and I keep encountering the error message "async task is not a function." Despite searching fo ...

Limit DerbyJS to re-rendering specific DOM elements

Currently, DerbyJS (visit http://derbyjs.com) functions by replacing everything in the body tag of the document each time a link is clicked. Is there a way to utilize the template, but replace only the content inside #main-content instead of refreshing th ...

Tips for creating a non-blocking sleep function in JavaScript/jQuery

What is the best way to create a non-blocking sleep function in JavaScript or jQuery? ...

Enable direct download from external servers

I'm in search of a way to prompt a download (by right-clicking and selecting "save as") for both mp4 and flv files. The challenge is that these files are not hosted on my server, they are direct links from external websites. I have tried using .htacce ...

Discover the process of enhancing features in an Angular component with JavaScript functionality

I am currently working on a shopping cart project and I need to implement the functionality to add products to the cart. Can Angular scripts be used in the way shown in my code snippet, or is there another solution that may work better? <div> < ...

Developing a Monitoring-Frontend Application with backbone.js

I am in the process of developing a tool for monitoring and analyzing statistics. The current setup is as follows: Collector-Backend: This component receives queries in JSON format from the frontend, fetches and stores them in a cache, and then notifies ...

Exploring Nested JSON Data with Pandas

Here is a JSON string that I need to work with: { "2022-09-28T00:45:00.000Z": [ { "value": 0.216, "plantId": "27050937", "man": "pippo" }, ...

Implementing new updates to an object without affecting existing values in Vue.js 2

I am currently facing an issue with updating values for an object received in a payload before saving it to the database. Despite making changes, the new values are not being persisted correctly. I am utilizing Vue.js 2 for this task. How can I effectively ...

Creating a simulated class within a function utilizing Jest

Currently, I am in the process of testing a controller that utilizes a class which functions like a Model. const getAllProductInfo = (request, response) => { const productInformation = new ProductModel().getAll(); response.status(200) resp ...

Dnd-kit: item loses its place in line when dragged over Droppable area

I've encountered an issue while using @dnd-kit. The sorting function works smoothly (e.g. when I drag the 1st element, it sorts correctly), but once I reach a droppable element (green Thrash), the sorting breaks and the 1st element snaps back. You ca ...

What should be done in Android when the app crashes due to incoming HTML content?

If I register using an email and password, the process is successful if the email exists within the domain. However, if a malformed email address like [email protected] is used, it returns HTML and crashes my app. How can I handle this issue? publi ...

NodeJS assert.AssertionError: How can I eliminate this error?

For my school project, I decided to create a web service using IBM Bluemix. However, I encountered an "assert.AssertionError" when attempting to run the code with "npm start" in the Windows 10 Command Prompt on my localhost. Can someone help me understan ...

Navigate directly to a designated element in a React component without the need to scroll when clicking a link

When viewing a user's profile in React, clicking on an image currently scrolls to that specific image within the entire images page. However, I am looking to modify this behavior so that it navigates directly to the image element without any scrolling ...

Every page on Nextjs displaying identical content across all routes

I recently deployed a Next.js app using docker on AWS infrastructure. While the index page (/) loads correctly, I've noticed that the content of the index is also being loaded for every other route, including api routes, as well as the JavaScript and ...

Localization support is working partially in a Node Express application that uses Handlebars for templating

Whenever I visit a URL with the ?lang=en query parameter, the English translation is never used. However, the Hungarian text changes work perfectly fine, displaying text to test on Hungarian in the default "hu" language without any issues. What could be ca ...

Unable to display results in React Native due to FlatList not being shown

I'm a beginner to React Native and I'm attempting to create a simple flatlist populated from an API at , but unfortunately, no results are displaying. Here's my App.tsx code: import React from 'react'; import type {PropsWithChildre ...