"Unleashing the Power of Effortless Object Unwr

Looking for a better way to convert a raw json snapshot from Firebase into a JS class. My current method is lengthy and inefficient. Does anyone have a more optimal solution?

Class:

class SuggestedLocation {
  country_slug
  region_slug
  slug
  marker_type
  typeInType
  geometry
  properties
  type
  id
  constructor(country_slug, region_slug, slug, marker_type, typeInType, geometry, properties, type, id) {
    this.country_slug = country_slug
    this.region_slug = region_slug
    this.slug = slug
    this.marker_type = marker_type
    this.typeInType = typeInType
    this.geometry = geometry
    this.properties = properties
    this.type = type
    this.id = id
  }
}

Current unwrapping technique:

static fromSnapshot(snapshot) {
let suggestedLocations = [new SuggestedLocation()]
if (snapshot.exists()) {
  const value = snapshot.val()
  // Monster loop with nested objects - currently inefficient
}
return new SuggestedLocationsObject(suggestedLocations)

}

Example Json:

{
  "united-kingdom" : {
    "calderdale" : {
      "rossendale-way" : {
        "accommodations" : {
          "Campground" : {
            "zO3HxZVELbd" : {
              "geometry" : {
                "coordinates" : [ -2.1901328761018704, 53.65022995288969 ],
                "type" : "Point"
              },
              "properties" : {
                "marker-color" : "#6e875f",
                "marker-size" : "medium",
                "marker-symbol" : "lodging",
                "name" : "",
                "place_id" : "zO3HxZVELbd",
                "plus_code" : ""
              },
              "type" : "Feature"
            }
          }
        }
      }
    }
  }
}

Answer №1

To analyze your snapshot data more efficiently, you can utilize the Object.entries method instead of just using Object.keys. This will allow you to retrieve both keys and values at once.

In addition, consider employing the map and flatMap functions to generate an array of instances of SuggestedLocation without explicitly using push.

If you find yourself bothered by multiple assignments to this.*, you might want to alter the constructor signature to accept an object as input rather than individual values. Then, use Object.assign for a streamlined transfer of values.

Regarding the initial element with undefined properties in the array of SuggestedLocation instances, its purpose may be related to scenarios where snapshot.exists() returns false. In such cases, this empty entry serves a specific function. However, it is unclear why this dummy entry is necessary when actual data is present.

Below is the code implementing the aforementioned concepts using plain JavaScript (non-TypeScript):

class SuggestedLocationsObject extends Array {
  constructor(arr) {
    super();
    Object.assign(this, arr);
  }
}

class SuggestedLocation {
  constructor(obj) {
    Object.assign(this, obj);
  }
}

function fromSnapshot(snapshot) {
    return new SuggestedLocationsObject(
      !snapshot.exists() 
      ? [new SuggestedLocation()] 
      : Object.entries(snapshot.val()).flatMap(([country_slug, regionSlugs]) =>
          Object.entries(regionSlugs).flatMap(([region_slug, slugs]) =>
            Object.entries(slugs).flatMap(([slug, markerTypes]) =>
              Object.entries(markerTypes).flatMap(([markerType, accomAmenityTypes]) =>
                Object.entries(accomAmenityTypes).flatMap(([accomAmenityType, typeInTypes]) =>
                  Object.entries(typeInTypes).flatMap(([typeInType, ids]) =>
                    Object.entries(ids).map(([id, {properties, geometry, type}]) =>
                      new SuggestedLocation({country_slug, region_slug, slug, markerType, typeInType, geometry, properties, type, id})
                    )
                  )
                )
              )
            )
          )
        )
    );
}

let data = {
  "united-kingdom" : {
    "calderdale" : {
      "rossendale-way" : {
        "accommodations" : {
          "Campground" : {
            "zO3HxZVELbd" : {
              "geometry" : {
                "coordinates" : [ -2.1901328761018704, 53.65022995288969 ],
                "type" : "Point"
              },
              "properties" : {
                "marker-color" : "#6e875f",
                "marker-size" : "medium",
                "marker-symbol" : "lodging",
                "name" : "",
                "place_id" : "zO3HxZVELbd",
                "plus_code" : ""
              },
              "type" : "Feature"
            }
          }
        }
      }
    }
  }
};

let snapshot = {
    exists() { return true },
    val() { return data }
}

let result = fromSnapshot(snapshot);

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

Accessing the Div id stored in a session parameter

Is there a way to store the id (div id) into a session variable? This is an example of my code below: <div class='fieldRow'>Options </div> <div id="abcde"></div> <div class='Row'> <?php $user_typ ...

When utilizing ASP.NET Core Razor pages for file uploads and utilizing AJAX Post to send the file to an IFormFile handler, the request

I have a straightforward task that involves uploading a file and using AJAX to post it to the Index page: <input type="file" id="file-selector" accept=".txt"> Here is the corresponding Javascript: const fileSelector ...

Regular expressions or regex can be used to match the initial letter or letters of various words

Struggling with regex? After searching for an hour, the best solution found was this one. Still unable to crack it though... Here's what I need: Have a JS array that needs to be filtered. The array looks like: [ 'Gurken halbiert 2kg', &a ...

Scala string: Unescaping made easy

I have come across numerous discussions on escaping strings, but none on de-escaping them. When working with Scala Play, my controller takes in a JSON request. I retrieve a string from it using the following code: val text: play.api.libs.json.JsValue = r ...

What are the steps to approve an Amazon Pay request for retrieving a "get checkout session"?

Exploring the integration of Amazon pay as a payment option for customers on my website has led me to encounter some challenges with understanding the request headers required for calling the Amazon Pay API. Attempting a request to 'https://pay-api.a ...

Error: Unable to parse JSON field value due to an unexpected OBJECT_START

Currently in my coding project, I am utilizing node and mongoose to update a Watson rank and access the database. My goal is to insert multiple documents into the collection. While I can successfully add a single document, I encounter issues when creating ...

Tips for producing/reserving cropped images from a photo? (includes converting images to base64 format)

Imagine having two square datasets taggedImages: { 0: {id:0, left:100, top:100, thumbSize:100, type: 'A', seasons: ['All', 'All']}, 1: {id:1, left:200, top:200, thumbSize:100, type: 'B', seasons: ['All&apo ...

Tips on managing ajaxStart and ajaxStop events the Angular2 way

I am seeking a way to trigger events similar to JQuery's ajaxStart and ajaxStop. While I found a partial solution on how to set default HTTP headers in Angular 2 here, I have managed to handle the ajaxStart event for now. Does anyone have any soluti ...

Troubleshooting the Vue.js component rendering issue

I am trying to display only one object from the data on firebase using [objectNumber]. I want to show {{ligler[1].name}} in the template, but it is causing errors: Error when rendering component Uncaught TypeError: Cannot read property 'name' o ...

JavaScript: Unusual behavior discovered in forEach iteration

Here's the code snippet I'm having trouble with: someArray.forEach(x => { // do something console.log(‘calling api for ‘ + x); callAnHttpApiAsync(...); sleep(10); }); The issue lies in the asynchronous nature of the HTTP API call within ...

Guide to transforming Amazon Ion object into JSON object using Go Lang

In my search for a solution, I have encountered the challenge of converting an Amazon Ion object to JSON in Go Lang. The issue arose while developing a DAO layer for Amazon QLDB. My approach involved using a Go Struct with both json and ion aliases: type P ...

"Effortlessly emptying the text field with material-ui in React

I need assistance with clearing the content of two text fields and a button using Material-UI in React-JS. I am new to React and unsure how to achieve this. Below is the code I currently have: import React from 'react'; import RaisedButton from ...

Add an array as a nested child within another array using node.js and JavaScript

Description: I execute a MySQL query to retrieve rows from a table > connection.query(q2,function(err,rows){...} Assuming the rows have a structure like {id:",,,", time:"..." etc:"cc"} For each row, I then query another table to fetch additional dat ...

How can I intercept/manage the back button of the browser in React-router?

Utilizing Material-ui's Tabs, which are controlled, I am implementing them for (React-router) Links in the following manner: <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/> <Tab value={1} label="users ...

Increase the value of a number using jQuery

When using jquery to animate a random number increment from 0001 to 1000, the issue arises when reaching the number 0077. The final number displayed is 77 instead of 0077. Is there a solution to ensure the format remains as 0077? Your help is appreciated. ...

How can you calculate the number of elements in a jQuery array and iterate through each of them?

After extracting a string from a mySQL query with PHP, my AJAX script comes into play. This string is then dissected and placed into a jQuery array. The results are displayed on the screen using .html() The length of this array can range from zero items t ...

Identify which anchor tag from the group with the matching class was selected and retrieve its unique identifier

There are multiple anchor tags with the same class in my code. <a href='' id='id1' class='abc'>Link 1</a> <a href='' id='id2' class='abc'>Link 2</a> <a href='&apos ...

Using Python to Populate an Array Inside a JSON Object

The JSON below shows a structure with file name and function details: post = { "file_name" : file_name, "function" : [{ "func_name" : func_name, "start_line" : start_line, "end_line" : end_line }] } In my Python script, I am attempti ...

Yahoo Finance provides information on all currencies with the Kuwaiti Dinar (KWD) as

In my application, I need to fetch currency conversion rates daily with a base currency of KWD. After exploring Yahoo Finance and other free providers, it seems that by default, Yahoo shows the base currency as USD or requires currency pairs in the format ...

The express app.get middleware seems to be malfunctioning due to a 'SyntaxError: Unexpected end of input'

Currently, I'm diving into an Express tutorial on YouTube but hit a roadblock with middleware that has left me bewildered. In my primary file, the code looks like this: const express = require('express'); const path = require('path&ap ...