Mapping over an array and ignoring any undefined properties in a dynamic object

Looking for a way to dynamically create objects in the 'map' function to reduce the final array size. The goal is to avoid adding properties with undefined values. For example, if 'offst: undefined', skip this property but add others with proper integer values. Is there a way to achieve this without looping through the array again? The array is quite large with over 150k entries, so performance is a concern.

this.mapData = this.mapData
                .map((e) => ({
                    p: e.p,
                    lat: e.lat,
                    lng: e.lng,
                    y: Object.keys(e.values)[0],
                    ct: Object.values(e.values)[0].ct, // include ct: only if not undefined
                    cp: Object.values(e.values)[0].cp,
                    w: Object.values(e.values)[0].wp,
                    offst: Object.values(e.values)[0].offst,
                    onst: Object.values(e.values)[0].onst,
                    ertn: Object.values(e.values)[0].ertn,
                    ertl: Object.values(e.values)[0].ertl,
                    dst: Object.values(e.values)[0].dst,
                    ft: Object.values(e.values)[0].ft,
                }))
                .filter((item) => item.chargersTotal !== 0);

            return this.mapData;

Sample JSON data:

[
   {
      "p":"BA1 2RU",
      "lat":"51.38934",
      "lng":"-2.364467",
      "values":{
         "2019":{
            "ct":0.0
            "dst":5.0
            "onst":1.0
         }
      }
   },
   {
      "p":"BA10 0AA",
      "lat":"51.112275",
      "lng":"-2.453865",
      "values":{
         "2019":{
            "offst":1.0,
            "ct":1.0
         }
      }
   },
   {
      "p":"BA10 0AB",
      "lat":"51.112463",
      "lng":"-2.454067",
      "values":{
         "2019":{
            "ct":0.0
         }
      }
   }
]

Answer №1

Utilize ellipses to incorporate Object.values(e.values)[0] into the object you are sending back. This way, it will only include the properties that are actually present.

this.updatedData = this.updatedData
  .map((e) => {
    let mainKey = Object.keys(e.values)[0];
    let mainValue = e.values[mainKey];
    return {
      x: e.x,
      latitude: e.latitude,
      longitude: e.longitude,
      z: mainKey,
      ...mainValue
    };
  })
  .filter((entry) => entry.count !== 0);

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

The animation is not updating quickly enough

I'm working on a navigation bar that sticks to the top of the page. As the user scrolls down, I want the bar to shrink, and when they scroll back up, it should return to its original size. Issue: The problem I'm facing is that when the user quic ...

The integration of VueJS with Axios and the Google Maps API

Currently following [this][1] guide to develop a Google Map and now I am looking to execute a GET request with Axios: axios.get("http://localhost:8080/mapjson").then(function(response) { }) in order to integrate the information from my JSON file into the ...

The anchor link is not aligning properly due to the fluctuating page width

Seeking help to resolve an issue I'm facing. Maybe someone out there has a solution? The layout consists of a content area on the left (default width=70%) and a menu area on the right (default width=30%). When scrolling down, the content area expand ...

"Trouble with Express.js: CSS isn't loading, yet HTML displays

Click here to view folders and files server.js is the code I have created so far //importing packages const express = require('express'); const admin = require('firebase-admin'); const bcrypt = require('bcrypt'); const path = ...

Concealing or revealing an image with jQuery when hovering

I currently have 3 <a> tags within my html, each containing 2 images. Specifically, the greyscale images are the ones that are visible while the colored ones are set to display:none. I am aiming to achieve a functionality where upon hovering over th ...

Is the ClientScriptmanager operational during a partial postback?

After successfully completing an ASP.NET operation, I want to automatically close the browser window. The following code is executed by a button within an Ajax UpdatePanel: Page.ClientScript.RegisterClientScriptBlock(typeof(LeaveApproval), "ShowSuccess", ...

Convert JSONX data into the standard JSON format

I have extracted XML data from my database and am looking to convert it to JSON format. Utilizing an IBM DataPower database, the process involves converting the XML to JSONx before using IBM's default translator to further convert it into JSON. My cu ...

Send a React component to another component as a prop

I am looking to pass the entire parent component as props to its child component. However, when attempting to pass data from parent to child, I ended up importing the child into the parent. Is there another way to achieve this? Any suggestions on how I c ...

Do AngularJS routes allow the use of special characters in URLs?

Issue at hand: Every time I enter http://localhost:53379 in the browser, it redirects me to http://localhost:53379/#/. Why is the /#/ being added? angular .module('app', ['ngRoute', 'ngStorage']) .config([&apo ...

Can jQuery.jScrollPane be set to consistently display a vertical scroll bar?

Can jQuery.jScrollPane be configured to consistently display a vertical scroll bar? Is there a hidden setting or API function that can achieve this? Ideally, without needing to adjust the content pane's height or other properties. ...

URL Construction with RxJS

How can I efficiently create a urlStream using RxJS that incorporates multiple parameters? var searchStream = new Rx.ReplaySubject(1); var pageStream = new Rx.ReplaySubject(1); var urlStream = new Rx.Observable.create((observer) => { //Looking to ge ...

Deciphering intricate JSON structures using PHP

In my current situation, I am receiving a server response with mixed data and now I need to handle it using PHP. Array ( [14424174] => Array ( [0] => Array ( [id] => 45 ...

Transferring data between AngularJS and non-AngularJS environments

Within my AngularJS application, the $scope.mydata variable holds some important data within a controller. I am currently working on a regular JSP page without any AngularJS functionality, but I need to access the data stored in the scope variable (mydat ...

Combining Array Elements to Create a Unified Object with Vue

Is there a way to transform an array into a list of objects? Transform [ { "currenttime":43481.46983805556, "moped":"30 minutes", "car":"1 hour" } ] to { "currenttime":43481.46983805556, "moped":"30 minutes", ...

Why do attributes of a directive fail to function within a different directive in AngularJS?

Trying to set attributes of the angularJS directive named ng-FitText within another angularJS directive called scroll-cards. Here's the approach I'm taking: In the code snippet below, the attribute data-fittest is being assigned from ng-FitText ...

In Angular, a white screen may suddenly appear if the scrolling speed is too fast

My experience has been primarily on Chrome. I've noticed that when I scroll for a long time, the data on the screen disappears briefly and then reappears after a few seconds. Is there a resolution for this problem? Thank you, ...

Achieving Dynamic Center Alignment of Filtered Node in SVG Using D3

I am currently implementing filter functionality for my d3 graph. The goal is to allow users to search for a specific node by label or ID, then re-render the graph to display the entire structure with the filtered node positioned at the center of the SVG e ...

The presence of v-if does not depend on the model value to toggle the element

I have a scenario where I want to hide the dropdown menu for US states if a different country other than the US is selected. The code snippet I am using to achieve this functionality is shown below: <b-row v-for="demo in demographics" :key=&qu ...

Switch back and forth between two different function loops by clicking

I have implemented two sets of functions that animate an SVG: one set runs in a vertical loop (Rightscale.verticalUp and Rightscale.verticalDown) and the other in a horizontal loop (Rightscale.horizontalUp or Rightscale.horizontalDown). On clicking the SVG ...

Dynamic calendar with flexible pricing options displayed within each cell

I've been wracking my brain over this issue for quite some time now, but still can't seem to find a solution! Is there a React Calendar out there that allows for adding prices within the cells? I simply want to show a basic calendar where each c ...