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

Updating chart.js data seems to be presenting some challenges

Need help fetching data with an AJAX request to update chart.js. The AJAX request is working fine, but the response doesn't update the chart. This is how I fetch the data: <script type="text/javascript"> $(document).ready(function(){ $("#da ...

Display the two values of an object pair using ng-repeat in AngularJS

I have an array of objects structured like this: myCtrl.siteNameLabels = myCtrl.actual.map(function (value, index) { return { actualSite: { actualSiteName : value, actualSiteData: myCtrl.tableData[index] }, ...

Using JSON Filtering with React

I am currently working on fetching JSON data and implementing a filtering feature for the displayed content. An error that I am encountering is: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined Any insights on what might be ...

Emit data asynchronously upon returning

In my node.js application, I have a background process implemented using the EventEmitter. Here is a snippet of how it is used: var event = { returnValue: undefined }; eventEmitter.emit('name', event, argument); return event.returnValue; // This ...

What is the best way to delete a parent table row in React JS when the child "delete" button is clicked?

Struggling with hiding a table row in my React JS app upon clicking the "delete" button. The functions causing issues are: ... changeHandler: function(e) { ... }, deleteHandler: function(e) { e.currentTarget.closest("tr").style.visibility = "hidden"; } ...

When reference variables are utilized before being parsed, what happens?

I'm a beginner learning Angular and have a question regarding the use of reference variables. Here is an example code snippet: <div class="bg-info text-white p-2"> Selected Product: {{product.value || '(None)'}} </div> <di ...

Exclude specific outcomes within a nested document in MongoDB

I have a situation where I need to query a list of items and only retrieve the ones that correspond to a specific ID in the provider_cost_dict. Essentially, if I input providerId = 10001, then only the items with a matching entry in the provider_cost_dict ...

It is imperative that the 'Access-Control-Allow-Origin' header value in the response is not set to '*' when the request's credentials mode is 'include'

I am currently working on establishing a connection using socket.io between Angular and a Node.js Server Within Angular, I have set up a new socket by importing socket.io-client and connecting it as follows: import * as io from 'socket.io-client& ...

Retrieve recently appended DOM elements following the invocation of createComponent on a ViewContainerRef

I have a current function in my code that dynamically creates components and then generates a table of contents once the components are added to the DOM. This service retrieves all h3 elements from the DOM to include in the table of contents: generateDy ...

Exploring A-Frame VR: Understanding the Distinction between Cursor and Raycaster

I'm in the process of developing a WebVR project that allows users to interact with the environment by 'clicking' on entities. Can you explain the distinction between using the cursor fuse attribute and the raycaster for interaction? ...

Utilize the Power of React.js and Express.js to Send Emails

After building a web app using React.js in ES6, I found myself wanting to add a "Contact Us" page that allows users to send an email. However, as a newcomer to React, I discovered that React itself cannot directly send emails. Following tutorials with node ...

Creating a React component with a reference using TypeScript

Let's discuss a scenario with a reference: someReference; The someReference is essentially a React component structured like this: class SomeComponent<IProps> { getData = () => {}; render() { ...some content } } Now, how c ...

Angular Material Clock Picker for 24-Hour Time Selection

Struggling to find a time picker component that supports the 24-hour format for my Angular 14 and Material UI application. Can anyone help? ...

Is there a way to extract the properties of a CSS class from a stylesheet and convert them into a hash using JavaScript or jQuery?

I am exploring a way to extract key value pairs from a CSS stylesheet related to a specific class or id into a JavaScript object for data accessibility. It is important to mention that I do not intend to apply this class directly to any DOM elements. In ...

JavaScript code for transitioning between a thumbnail and a full-width image header on a webpage

I am looking to create transitions in NextJs that involve a smooth shift from a thumbnail image to a full-screen header when clicking on a project from the home page. I prefer utilizing internal routing rather than React Router, but I am open to using that ...

Displaying HTML content using Typescript

As a newcomer to typescript, I have a question regarding displaying HTML using typescript. Below is the HTML code snippet: <div itemprop="copy-paste-block"> <ul> <li><span style="font-size:11pt;"><span style="font-family ...

An easy way to incorporate a fade-in effect for every word in a text

I am trying to make the text "Eat. Sleep. Repeat." slide up and fade in one word at a time. I have experimented with various methods like anime.js, keyframes, and adding css classes, but so far none of them have worked for me. Here is the code I currently ...

Executing the JavaScript function on a batch of 6 IDs at once (should return every 6 calls?)

I'm curious if there's a function available that can group called data into sets of 6. Here's the expanded version of the code var currentResults; function init() { getProducts(); } function getProducts() { $.ajax({ url:" ...

Configuring Access-Control-Allow-Origin does not function properly in AJAX/Node.js interactions

I'm constantly encountering the same issue repeatedly: XMLHttpRequest cannot load http://localhost:3000/form. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefor ...

Transform a list of H1..6 into a hierarchical structure

I have a task to convert H1 to H6 tags from a markdown file into a JavaScript hierarchy for use in a Table of Contents. The current list is generated by AstroJS and follows this format [{depth: 1, text: 'I am a H1'}, {depth: 2: 'I am a H2}] ...