in AngularJS, check for object attributes existence before proceeding to use them

Currently, I have a filter function that is designed to check the latitude and longitude distance of objects within an array against the range selected by the user. However, there is a problem in which some objects within the array do not possess latitude and longitude attributes at all. This issue causes the filter to malfunction. Is there a possible solution to skip over objects lacking latitudinal and longitudinal values or those with both latitudes and longitudes set to 0?

Here is the snippet of code:


function distanceFromFunc(distanceFrom) {
  var m;
  var n;
  var positionContainer = [];
  var docLat;
  var docLon;
  var rowIdFromObj;
  var rowObj;
  var rowsArray;

  if (distanceFrom === "1") {
    vm.selectedRadius = 1609.344 //1 mile
  } else if (distanceFrom === "2") {
    vm.selectedRadius = 3218.688 //2 miles
  } else if (distanceFrom === "5") {
    vm.selectedRadius = 8046.720 //5 miles
  } else if (distanceFrom === "10") {
    vm.selectedRadius = 16093.440 //10 miles
  } else if (distanceFrom === "20") {
    vm.selectedRadius = 32186.880 //20 miles
  } else if (distanceFrom === "50") {
    vm.selectedRadius = 80467.200 //50 miles 
  } else if (distanceFrom === "999999") {
    vm.selectedRadius = 0
  };

  function filterByDist(value) {
    console.log("VALUE IS ------>" + JSON.stringify(value));
    var dist = distance(myLat, myLon, value.locations[0].Lat, value.locations[0].Long);
    if (dist <= distanceFrom) {
      console.log("the dist is: " + dist);
      return value
    };
  };

  var digestedArray = originalData2.filter(filterByDist)
  $scope.locatorGridData = digestedArray;
}; 

The point where it seems to break occurs on this line:

var dist = distance(myLat, myLon, value.locations[0].Lat, value.locations[0].Long);

Answer №1

In order to fix the issue, just change the problematic line to:

var dist;
if (value.locations && value.locations.length &&
    value.locations[0].Lat && value.locations[0].Long){
    dist = calculateDistance(myLat, myLon, value.locations[0].Lat, value.locations[0].Long);
}

Answer №2

Before triggering the distance method, it is recommended to perform a quick verification:

function filterByDist(value) {
  if (value.locations[0].Lat && value.locations[0].Long) {
    var dist = distance(myLat, myLon, value.locations[0].Lat, value.locations[0].Long);
    if (dist <= distanceFrom) {
      return value
    }
  }
}

It is assumed that the potential error lies in the specified location, but there is a possibility that an error could occur at that point.

Answer №3

This block of code verifies the existence of certain conditions before calculating distance:

  • Check if value and value.locations are both defined

  • Ensure that Lat and Long are present

The actual calculation of distance will only occur if all these criteria are met.

if(value && value.locations.length && value.locations[0].Lat && value.locations[0].Long) {
     // Perform distance calculation here
}

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

Content OverFlow: DropDown Menu is not overlapping the content, but rather pushing it downwards

In my webpage, I have a drop-down menu that traditionally pushes the content below it down to make space for its items. However, I want the drop-down to overlap the contents below without affecting their position. I've tried various solutions, such a ...

Having trouble loading the Google API using getScript. Is displaying a ReferenceError message: "Variable google not found."

I am attempting to dynamically load the Google API using the getScript() method for implementing a "Place Autocomplete Address Form". For more information, you can visit this link: https://developers.google.com/maps/documentation/javascript/examples/places ...

Guide on displaying the value of an element in a Vue modal

I am working with a list of items displayed as <li> elements in a loop. When one of these elements is clicked, I would like a modal box to open up displaying specific content related to that particular element. The following data represents the item ...

Encountering a Next.js Strapi error. TypeError: Fetch request unsuccessful

An error occurred during module build: UnhandledSchemeError: The plugin does not support reading from "node:assert" URIs (Unhandled scheme). Webpack natively supports "data:" and "file:" URIs. You might require an extra plugin to handle "node:" URIs. ...

Removing values in javascript for checkboxes that are not selected

Here is the JavaScript Code : var clinicalStat; var id; var val; var clinicalVals; $(":checkbox").click(function() { //alert(" you checked"); if ($(this).is(':checked')) { var checked1 = $(this).val(); //Inital value of check ...

Animating the change in Slider value with Material-UI in React

Recently delving into React, I encountered my first challenge that has been consuming my time for hours. I'm working with a Slider component from Material-UI and seeking to animate the value changes. Currently, when clicking on a button, the slider i ...

What could be causing my code to become unresponsive when using a for loop compared to a loop with a specific

After spending a solid 4 hours on it, I finally managed to figure it out. There were no errors popping up, so I resorted to using the debug feature which unfortunately didn't provide much insight. Without any error messages to guide me, I wasn't ...

"Duplicate content issue with ng-transclude causing element to render twice

Why is the transcluded directive displaying Name inside directive = Frank twice? I believed I had a good grasp on transclusion, but this specific scenario has left me puzzled. Check out this fiddle for more details <div ng-app="myApp" ng-controller=" ...

Exploring the depths of JavaScript JSON elements

After processing my PHP code, it generates a JSON output that contains multiple entries in the same structure. Here is an example with two entries: { "0": { "campaign_id": "31", "title": "new title", "description": "new descrip ...

Is it considered secure to replace an object within an array when working with Angular bindings?

In my Angular JS project, I have incorporated a form with a reset function. Whenever I begin editing an item on the form, the setPrimarySelectionEditEntry function is invoked. The primarySelectionEntry variable contains the object bound to the controls. ...

Customize the CSS for a Material UI popover styling

I am currently working with a Material UI popover and attempting to apply CSS styles to it. This is the code for my popover component: import React, { memo, useCallback } from 'react'; import PropTypes from 'prop-types'; import { ...

What is the method for one service to observe the data of another service?

Currently, I have two services in my application that fetch different types of data from the server. Each service has controllers that utilize $scope.$watch to monitor changes in the data. In an attempt to enhance my application's functionality, I in ...

Extract data from the HTML source code in JavaScript and transfer it to a personalized JavaScript variable within Google Tag Manager

Running an e-commerce website on Prestashop and facing an issue with data layer set up. Instead of a standard data layer, the platform generates a javascript variable called MBG for Enhanced E-Commerce implementation. <script type="text/javascript"> ...

Swap the text within the curly braces with the div element containing the specified text

I have an input and a textarea. Using Vue, I am currently setting the textarea's text to match what's in the input field. However, now I want to be able to change the color of specific text by typing something like {#123123}text{/#}. At this poin ...

Attempting to retrieve information from my MongoDB database and populate it into a <table> structure on a web page

My objective is to extract data from a MongoDB database and display it in an HTML table. Specifically, I am trying to retrieve information from the hangman database's players collection, which contains fields for name and score. Can anyone help me ide ...

Tips for utilizing New FormData() to convert Array data from an Object for executing the POST request with Axios in ReactJs

When working on the backend, I utilize multer to handle multiple file/image uploads successfully with Postman. However, when trying to implement this in ReactJS on the frontend, I find myself puzzled. Here's a sample case: state = { name: 'pro ...

When using the hasMany/belongsTo relationship in VuexORM, the result may sometimes be

I have carefully followed the documentation and set up 2 models, Author and Book. The relationship between them is such that Author has many Books and Book belongs to an Author. However, despite having the author_id field in the books table, the associatio ...

`ACCESS DENIED: Unauthorized access attempt detected in Node.js``

When attempting to connect, MySQL is establishing a connection with an unfamiliar IP address. Refer to the code below: .env MYSQL_HOST=domain.example.com MYSQL_USER=**** MYSQL_PASSWORD=**** MYSQL_DB=**** MYSQL_PORT=3306 connection.js const mysql = requir ...

extract information from an external JSON document

I have a JSON file filled with data, along with a JSX file containing a button and a div. I'm looking to extract the data from the JSON file and display it in the div when the button is clicked. However, I'm at a loss on how to achieve this. The ...

What could be causing the issue with my validation for alphabetical input?

I am currently working on a registration form that only accepts alphabetical input. However, I am facing an issue where my error message appears regardless of whether I input an alphabetical or special character. According to my understanding, the code sho ...