Organizing Firestore data into structured JSON format

For my database collection, I am utilizing a cloud function to download it as a JSON file.

Here is the code snippet:

exports.csvJsonReport = functions.https.onRequest((request, response) => {
  const db = admin.firestore()
  const userAnswers = db.collection('/surveys/CNA/submissions')
  return (
    userAnswers
      .get()
      .then(querySnapshot => {
        let answers = []
        querySnapshot.forEach(doc => {
          const answer = doc.data()
          answers.push({ ...answer.answers, ...answer.anonUser })
        })

        response.setHeader('Content-disposition', 'attachment; filename=cna.json')
        response.set('Content-Type', 'application/json')
        response.status(200).send(answers)
      })
      .catch(error => {
        console.log(error)
      })
  )
})

In most cases, I am interested in only the value field. However, sometimes the value is nested within another field, in which case I need both the value and name.

Current output:

[{
"2": {
      "loopIndex": null,
      "questionType": "multiChoice",
      "value": "Farm owner",
      "id": 1
    },
"7": {
      "1": {
        "name": "Enviroment management",
        "questionType": "responsiveMultiCheckBox",
        "valueId": 4,
        "value": "My top priority right now",
        "id": 1
      },
      "2": {
        "questionType": "responsiveMultiCheckBox",
        "valueId": 3,
        "value": "One of my top priorities",
        "id": 2,
        "name": "Financial management"
      },
      "3": {
        "value": "My top priority right now",
        "id": 3,
        "name": "People management",
        "questionType": "responsiveMultiCheckBox",
        "valueId": 4
      },
      "4": {
        "name": "Reproduction management",
        "questionType": "responsiveMultiCheckBox",
        "valueId": 4,
        "value": "My top priority right now",
        "id": 4
      },
      "5": {
        "name": "Feed management",
        "questionType": "responsiveMultiCheckBox",
        "valueId": 4,
        "value": "My top priority right now",
        "id": 5
      }
    },
}]

Desired output:

[{
    "2": {
          "value": "Farm owner",
        },
    "7": {
          "1": {
            "name": "Enviroment management",
            "value": "My top priority right now",
          },
          "2": {
            "value": "One of my top priorities",
            "name": "Financial management"
          },
          "3": {
            "value": "My top priority right now",
            "name": "People management",
          },
          "4": {
            "name": "Reproduction management",
            "value": "My top priority right now",
         },
          "5": {
            "name": "Feed management",
            "value": "My top priority right now",
          }
        },
    }]

I attempted to use:

answer.answers.map(questionId => {
            return console.log('value', questionId.value)
          })

However, the error message "answers.answers.map is not a function" was encountered.

Answer №1

Check out this practical example on JSFiddle: https://jsfiddle.net/uekbhta6/2/

let result = {}; 
// This code assumes that the answers array always contains one object with additional data    
for (let id in answers[0])
{
    // If the value exists at the top level, add it to the result
    if (answers[0][id].value) 
    {
        result[id] = answers[0][id].value;
    }
    // If not, loop through the second level and store the name/value pairs in the result
    else
    {
       result[id] = {};
       for(let id2 in answers[0][id])
       {
          result[id][id2] = {
                name:answers[0][id][id2].name,
              value:answers[0][id][id2].value
          };
       }
    }   
}
// Encapsulate the result in an array and display it
console.log([result])

Although this code could be optimized using Array.reduce(), for now simplicity prevails. Time for some rest!

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

Obtain the name of the client's computer within a web-based application

I am working on a Java web application that requires the computer name of clients connecting to it. Initially, I attempted to retrieve this information using JavaScript and store it in a hidden form field. However, I discovered that JavaScript does not hav ...

Having trouble getting tailwind dark mode to work on next.js?

I have set up a custom boilerplate using next.js(10.0.5) with preact(10.5.12), typescript(4.1.3), and tailwind(2.0.2). I am attempting to incorporate a dark mode feature from Tailwind. I followed the instructions from next-themes in order to add the dark ...

"Assertj is used to compare the extracted values, specifically when they are arrays

My situation involves requesting sets of names from two different systems and checking if they are equal, regardless of the order. The code below seems to work fine: assertThat(asList(assertThat(firstJSON) .flatExtracting("innerObject") .extractin ...

What is the best method for extracting a value from a JSON file within an array using electron and node.js?

Hey there, I'm currently working with a JSON file that contains an array of value sets. I'm trying to figure out how to extract the first value from the initial set, specifically the value 3 under the key "pink". This is all being done in Node.js ...

The CSS files are not loading automatically in my React application using Vite

I am facing an issue with importing css and js files into a view in React using vite. The styles are not loading properly, and I have to keep commenting and uncommenting the imports in my code for them to be recognized when entering the view. Below is a s ...

Creating an HTTPS server that can be accessed via my specific IP address

My attempt to create ad hoc and OpenSSL based certificates in Python Flask was inspired by a tutorial I found on this website. I also explored the method of creating root CA, trusting it, and generating certificates as outlined on this GitHub thread using ...

What is the best method for uploading and saving a file using AngularJS and ExpressJS together?

I am using a library for AngularJS called angular-file-upload. Despite successfully setting it up and getting image uploads to work, I am facing an issue with passing the file to the server side (express js). Jade: input.form-input(ng-model="userAvatarFi ...

Are you facing difficulties while trying to utilize useContext in your React application?

I have a basic React application where I need to implement useContext. (by the way, I am using Vite + React) Below is the code for my Context.jsx file: import React, {useContext} from 'react'; const emailContext = React.createContext(); expor ...

Responsive design in Android does not function as intended

My goal is to create a responsive design for my website, but I am encountering issues with importing the CSS files into the HTML. When I try to view the site in both the Windows version of Chrome and the Android version, all I see is a white screen. I am c ...

What is the process for including a file in a request?

I've been encountering an issue while trying to upload a CSV file and send a request to an API. Despite attempting to do so via XHR, Unirest, and Axios, none of these methods seem to be working properly. Could there be something amiss with the impleme ...

Unlocking the secret to accessing state in a JavaScript file using VUEX

Can anyone help me figure out why I can't access the currentUser property from the state in my vuex store's user.js file? I'm trying to use it in auth.js, but when I write: store.state.currentUser.uid === ... This is the error message I&apo ...

Utilizing YouTube API information with AngularJS

I am currently working on a project where I need to fetch all the playlists from a specific channel and then display the name of each playlist in my AngularJS application. var myApp = angular.module('app', ['ngResource']); myApp.facto ...

Combining the elements within an array of integers

Can anyone provide insight on how to sum the contents of an integer array using a for loop? I seem to be stuck with my current logic. Below is the code I've been working on: <p id='para'></p> var someArray = [1,2,3,4,5]; funct ...

Obtain keys from a dictionary, nested dictionaries, and lists to determine the frequency of their appearance

My current project involves writing a code that extracts data from a JSON file in the form of nested dictionaries and lists. I am focused on retrieving all keys (results, x1, x2, x3, y1, y2, a1, b1) from the JSON and determining how many times each key app ...

Searching for IDs in an external file using JQ

I'm facing an issue with a lookup file that connects IDs between different systems: [ { "idA": 2547, "idB": "5d0bf91d191c6554d14572a6" }, { "idA": 2549, "idB": "5b0473f93d4e53db19f8c249" }, { "idA": 2550, "idB": "5d0 ...

Update the state within a different function in Vue.js

Just starting out with Vue.js and I'm trying to figure out how to update the component's state from a function in another file. I have a basic form with only an input file element. Once the user selects a file, the onChange handler will be trigg ...

Check if the content key Json exists by implementing Vue

Can anyone help me with checking the existence of "novalue"? For instance: { name: "maria", city_id: "novalue" .... } What would be the best way to do this in Vue? Should I use <div v-if="condition"> or a function? ...

Error in Bootstrap table implementation leading to truncation of tbody height due to data-detail-view property

I'm currently working on integrating Bootstrap-Table's detailView feature into my project. However, when I enable data-detail-view="true" for my table, the height of the table element shrinks to 0. Strangely, clicking on any column with ...

Guide to extracting a key from a nested key in Python

Hello, I'm currently trying to retrieve the value of a key nested within another key. For example: x = {"vegetables":[{"carrots":['15']},{"cucumbers":['20']}]} print(x.get("vegetables")) I h ...

Tips for updating the position on a website using AJAX

I am developing a website that pulls data from a MySQL database and showcases it on a map. How can I implement an automatic data refresh on the webpage every second? Should I incorporate my AJAX code within a timer function? Do I need to put the PHP scri ...