What is the best method to identify false values within the properties of a series of interconnected objects?

I am currently utilizing the Logical OR (||) operator to verify and assign values if they are not falsy in the following manner:

let locationDistrict =
                    result.results[0].address_components[2].long_name ||
                    result.results[0].address_components[1].long_name ||
                    result.results[0].address_components[0].long_name ||
                    'unknown district';

However, I encounter an error when result, result.results, result.results[0], or address_components is undefined:

Uncaught TypeError: Cannot read property [name_of_property] of undefined

To address this issue, I attempted using the Optional chaining (?) operator to access properties, as shown below:

let locationDistrict =
                    result?.results[0]?.address_components[2]?.long_name ||
                    result?.results[0]?.address_components[1]?.long_name ||
                    result?.results[0]?.address_components[0]?.long_name ||
                    'unknown district';

Unfortunately, it still fails to assign the default value 'unknown district'.

I managed to make the code functional by employing the Conditional (ternary) operator and checking for falsy values like so:

let locationDistrict =
                    (result && result.results && result.results[0] && result.results[0].address_components[2]) ? result.results[0].address_components[2].long_name :
                    (result && result.results && result.results[0] && result.results[0].address_components[1]) ? result.results[0].address_components[1].long_name :
                    (result && result.results && result.results[0] && result.results[0].address_components[0]) ? result.results[0].address_components[0].long_name :
                    'unknown district';

Nevertheless, I believe there must be a more elegant solution available. Why does the || operator not detect the 'undefined' value of the expression when any of its chained objects is undefined? How can I utilize the || operator effectively to check for falsy values within deeply nested properties of interconnected objects on the left-hand side operand?

Answer №1

Is this the information you seek?

let data = {};

let placeArea =
                    data?.details?.[0]?.location_attributes?.[2].long_descriptor ||
                    data?.details?.[0]?.location_attributes?.[1].long_descriptor ||
                    data?.details?.[0]?.location_attributes?.[0].long_descriptor ||
                    'unknown area';

console.log(placeArea)

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

Extracting specific keys from JSON data

I am working with an array named cols: var cols = ["ticker", "highPrice", "lowPrice","lastPrice"] // dynamic The JSON data is coming from the backend as: info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84} If I want to sel ...

Update overall font size to be 62% for a consistent look across the website

Recently, I developed a browser extension that adds an overlay button to the LinkedIn website. Everything was running smoothly until I discovered that LinkedIn uses a global font-size: 62,5% that completely messes up my design.. https://i.stack.imgur.com ...

Navigating through sections in NextJS-14: Utilizing useRef for seamless scrolling

In the past, I had developed an older portfolio website using Vite React + TS and implemented useRef for scrolling to sections from the Navbar. Now, my goal is to transition this portfolio to NextJS 14. I transferred my old components and style folders in ...

Changing the prototype of a generator function

TL;DR I am looking to enhance a generator function instance by adjusting its prototype, specifically the object received when calling a function*. Imagine I have a generator function: function* thing(n){ while(--n>=0) yield n; } Next, I create a ...

Browsing JSON data to pinpoint locations on a Google map

Trying to create a google map using jQuery and javascript with latitude and longitude values stored in a JSON file. Clicking on a state name should generate the map. Encountering an issue where only index[0] is being generated. The for loop seems to be ma ...

Leveraging a shared directory within an npm project

In my Vue project, I have multiple clients with similar components stored in a "common" folder structure: clients -- client1 ---- ... -- client2 ---- ... -- client3 ---- ... -- common ---- imports.js ---- ... Currently, each project has its own package.j ...

The Node.js Express server does not provide access to certain static files

I am currently utilizing the angularjs-gulp-browserify-boilerplate for my development environment on Windows 10. Once I run gulp in dev mode, static files are moved to the build directory: ./build |_js |_css |_img |_fonts |_lang In additio ...

Finding the average JSON value using d3.js

Here is the structure of a JSON file I am working with: [ {"id":1,"sex":"Female","programming":5, "project":7}, {"id":2,"sex":"Male","programming":8, "project":4}, {"id":3,"sex":"Female","programming":5, "project":6}, {"id":4,"sex":"Male","programm ...

karma is failing to run the test scenario

I am just starting out with karma and I'm having trouble running test cases. Below is my setup: karma.config.js module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) base ...

What is the most effective method to store temporary data within a backend panel as a sub-option?

Greetings! I have been delving into the world of programming for a while now, striving to enhance my skills. Currently, I am faced with a dilemma: Within my backend application, administrators have the capability to add courses to our website. One featur ...

How can I reset a CSS position sticky element using JavaScript?

I have created a page where each section fills the entire screen and is styled using CSS position: sticky; to create a cool layered effect. Check it out here: https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&hidenavigation=1&theme=dark ...

Is there a way to prevent users from copying data or switching tasks when using my program or website?

Is it feasible to develop a website or application for Windows desktop machines that can remain focused until the user completes a specific task? For instance, if my YYY app/website is open and I require the user to input some text, I want to restrict the ...

Using dynamic template URLs in resolving with Angular's UI-Router can provide flexibility

Currently, I have implemented a parent directive for an entire view to interchange templates based on the outcome of a promise. .directive('myDirective', function(myService) { var rootDir = '/path/to/templates'; return { ...

Convert the text inside a span element into a key-value object in JavaScript

How can I extract and save the text from a span element as key value pairs within a div? <div class="data-diff-span__composite-list-item__18c5zip data-diff-core__highlight-area__19c0zip"> <div class="data-diff-basic__class-row__4n ...

Encountering memory leaks and displaying repetitive data due to having two distinct observables connected to the same Firestore

I am currently utilizing @angular/fire to retrieve data from firestore. I have two components - one serving as the parent and the other as the child. Both of these components are subscribing to different observables using async pipes, although they are bas ...

Actions for jQuery's mouseenter and mouseleave events

I've implemented a jQuery script that controls the visibility of elements based on mouse events: $("#divid").mouseenter(function() { $('#divid').show(1000); }).mouseleave(function() { $('#divid').hide(1000); }); $("#hldiv" ...

Capturing an error within an asynchronous callback function

I am utilizing a callback function to asynchronously set some IPs in a Redis database. My goal is to catch any errors that occur and pass them to my error handling middleware in Express. To purposely create an error, I have generated one within the selec ...

Looking to resolve an issue that is arising in the antd tree component

Having trouble with the antd tree component - when searching and checking/unchecking a field, all previously selected data is unchecked. I want to only update the field that is currently being changed. Not sure how to fix this issue, any help would be appr ...

Capturing dynamic text from a URL using Protractor and Node.js

How can I extract the 'PR001-CC001234' segment from a URL using Protractor in Node.js? While I am able to retrieve the current URL and save it as a variable, I am seeking assistance in extracting the dynamic text at the end of the URL. http://exa ...

Mobile site's call button functionality is malfunctioning

For the telephone number on my mobile site, I employed the <a href="tel:+1800229933">Call us free!</a> code. However, it seems to be malfunctioning on several devices. Any insight on this issue would be greatly appreciated. Thank you. ...