Tips for dodging drawn-out sequences of periods

When working with nested objects using dot notation, it can be tedious to constantly check if each previous object exists.

I'm looking for a solution that avoids lengthy if chains like

if (a && a.b && a.b.c && a.b.c[0] ... ) { v = a.b.c[0]; }

The only alternative I've considered is using try catch blocks.

var v; try { v = a.b.c[0].d.e; } catch (e) {}

Is there a more effective pattern to handle this situation?

Answer №1

I believe you have already found the most elegant solutions.

However, it is important to note that in cases like obj.obj.string.length, your initial solution may not work if string === "". An empty string evaluates to false, triggering the && guard.

When it comes to handling strings, you could consider a method like this:

function getNestedProperty(obj, propChain) {
    var props = propChain.slice(0), prop = props.shift();
    if(typeof obj[prop] !== "undefined") {
        if(props.length) {
            return getNestedProperty(obj[prop], props);
        } else {
            return obj[prop];
        }
    }
}

var v = getNestedProperty(a, ["b", "c", 0, "d", "e"]);

Not the most aesthetically pleasing solution, I must admit :P

Out of all the options presented, using try...catch might just be the simplest approach.

Answer №2

Here's an interesting snippet for you to consider:

const checkNestedProperty = function (obj, prop) {

    const properties = prop.split('.'),
        temporary = obj;

    while (temporary && properties.length) {
        temporary = temporary[properties.shift()];
    }

    return !!temporary;
};

You can then implement it in your code like this:

if (data && checkNestedProperty(data, 'info.details.1')) { result = data.info.details[1]; }

Answer №3

The concept mentioned in your inquiry is commonly known as "optional chaining." Some programming languages like C# have already incorporated this feature, referred to as null-conditional operators, allowing for efficient expression short-circuiting:

var count = customers?[0]?.Orders?.Count();

Regrettably, optional chaining is not yet part of the current JavaScript specifications.

A Stage 1 proposal for optional chaining is under consideration and can be monitored through this link.

If implemented, you could simplify code snippets like...

a?.b[3].c?.(x).d

...instead of the longer alternative:

a == null ? undefined : a.b[3].c == null ? undefined : a.b[3].c(x).d

If you are willing to explore this feature at its early stage, consider using Babel plugin for optional chaining to integrate it into your project.

Answer №4

This solution may not be ideal, but it is effective and doesn't appear too messy:

var i = !a ? null : !a.b ? null : !a.b.c ? null : !a.b.c.d ? a.b.c.d.e;

The usage of ! serves to reverse the test flag in order to have the successful outcome as the final expression within the ?:. This allows for the chaining of conditions in this manner.

It is advisable to verify the operator precedence if implementing this technique seriously (I conducted some basic tests which seem accurate). Also, be prepared for some amusement from others if they come across this unconventional code in your program.

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

What's the best way to navigate across by simply pressing a button located nearby?

Hey there! I'm new to JavaScript and I'm working on a shopping list page for practice. In my code, I can add new items to the list, but what I really want is to be able to cross out an item when I click the "Done" button next to it, and then uncr ...

The setInterval() function is not functioning properly when used with PHP's file_get_contents

Currently, I'm encountering an issue while attempting to use the function get_file_contents() within a setInterval(). The objective is to continuously update some text that displays the contents of a file. Below is the code snippet: <script src="h ...

Endless Loop of Http Redirects in Node.js with Express

I need assistance with the code below which is meant to redirect all http traffic to https. // Implement redirect logic to ensure usage of https in production, staging, and development environments app.use((req, res, next) => { // Do not redirect to h ...

Ensuring correct association of values to avoid redundancies

There are 5 fields available for users to fill out on this form: Leave Code, From Date, Input Time1, To Date, and Input Time2. These variables are declared as a dates object in the .ts file, as shown below. interface Supervisor { name: string; code: s ...

Can the table be automatically updated on page reload?

My goal is to populate a table using $.ajax(), but the content is not showing up when the page first loads. Is there something missing in my implementation of the $.ajax() function? Here's the HTML structure: <div class="row"> <div clas ...

Exploring the power of Typescript functions within a traditional VueJS project

TL;DR: How can I import and use a typescript module into my plain js Vue-Components? I have a Vue 2 (not yet 3) project. In this specific project, I have made the decision to refactor some of the code logic into ES modules for improved testability and reu ...

The dropdown menu button stubbornly remains open and refuses to close

Having an issue with a dropdown menu button where it should open when clicked on the icon and close when clicking off the icon or on the icon again, but instead, it remains open. Here is a screenshot for reference: https://i.stack.imgur.com/UX328.jpg I&a ...

Guide on incorporating jQuery library files into existing application code with the npm command

Recently, I used a node JS yo ko command to create a single-page application using Knockout-JS. Following that, I proceeded to install jquery packages using the command npm install jquery The installation was successful. However, my current goal is to in ...

Leveraging Json data in Angular components through parsing

I am currently developing an angular application where I need to retrieve and process data from JSON in two different steps. To start, I have a JSON structure that is alphabetically sorted as follows: { "1": "Andy", "2": &qu ...

Issue with the select element in Material UI v1

I could really use some assistance =) Currently, I'm utilizing Material UI V1 beta to populate data into a DropDown menu. The WS (Web Service) I have implemented seems to be functioning correctly as I can see the first option from my Web Service in t ...

Steps to temporarily turn off Backbone.sync for a fresh model and then reactivate it once the user clicks the save button

I am currently working with a Backbone collection model that consists of sub-models as elements, along with views to edit it. My objective is to have the syncing functionality "turned off" initially when the model is created, so that the back end is not c ...

Utilizing jQuery.ajax to Send an Array of Objects to a PHP Function

In this scenario, an array of objects is represented as follows: rectangle[0].width = w; rectangle[0].height = h; rectangle[1].width = w; rectangle[2].height = h; rectangle[3].width = w; rectangle[3].height = h; ... We need to figure out how to send thi ...

Tips for adjusting the autocomplete maxitem dynamically

I am working on a multi autocomplete feature and I have the following code. Is there a way to dynamically set the maximum number of items based on the value entered in another text field? <script> $(function () { var url2 = "<?php echo SI ...

Listening for JS events on a CSS class called "int-only" which only accepts

Having an issue: I'm encountering a problem with this PHP code: <?php for($i = 0; $i < sizeof($floating_ips_json["floating_ips"]); $i++){ ?> <tr class="details-control-<?php echo $i; ?> cursor-pointer"> <t ...

Updating JSON when the color changes in Go.js can be achieved by implementing event listeners and

I've been using Go.js for creating Flow charts and saving the json data into a SQL database. However, I'm facing difficulties in updating the json data. Here is the code snippet: myDiagram.addDiagramListener("ChangedSelection", function (e1) { ...

Issue encountered: Cannot locate module: Error message - Unable to find 'stream' in 'C:devjszip-test ode_modulesjsziplib' folder

I am encountering an issue in my angular 7 application while using jszip v3.2.1. During the project build process (e.g., running npm start), I receive the following error message: ERROR in ./node_modules/jszip/lib/readable-stream-browser.js Module not fo ...

Tips on using JQuery to extract form field information from a drop-down menu, display it in a div, and then compare it with the subsequently

In my HTML file, I am using two dropdown lists and JQuery for validation. First, I need to save the selected items from both dropdown lists in a variable and then compare them with the next selection. If the data from both dropdown lists match, an alert m ...

The Webix component is experiencing a lack of refreshment

function refresh_group_items(){ //console.log("calling1"); window.setTimeout(function(){ $$("cfg").reconstruct() }, 3000); } $.ajax({ type: "POST", xhrFields:{ withCredentials: true }, beforeSend: function(reque ...

Can the MemoryRouter be successfully nested within the BrowserRouter in a React application?

I've been on a quest for some time now, trying to uncover whether it's feasible to utilize MemoryRouter solely for specific routes while maintaining the use of BrowserRouter in general. My goal is to navigate to a particular component without alt ...

Issues with JavaScript Content Loading in epub.js on a Website

Hey there, I'm currently experimenting with the epub.js library and trying to set up the basics. However, I'm encountering an issue where the ebook is not showing up in my browser: <!DOCTYPE html> <html lang="en"> <head&g ...