JavaScript's ability to call object properties at multiple levels allows for complex data

My approach involves using mongodb in conjunction with ajax calls for data retrieval. However, I have encountered an issue where the properties needed to generate HTML from JavaScript objects are sometimes missing. Consider this ajax call:

$.ajax({
        url: 'api/v1/mention/'+id,
        type: "GET",
        dataType: "json",
        data : {login : "demo"},
        success: function(mention) {
            display_mention_text(mention.texto);
        }
    });

While calling mention.texto in this case, it could also be mention.picture or any other property. The app crashes when these properties are undefined.

To address this issue, I have created a method that retrieves a property from an object and returns an empty string if it is undefined. Here are some examples of calling this method (the first argument is the object, followed by the properties):

get_property(mention,"text")
get_property(mention,"user","name")
get_property(mention,"picture")

The method is defined as follows:

function get_property(obj){
    var args = Array.prototype.slice.call(arguments),
     obj = args.shift();
    if (checkNested(obj,args)) {
       //what should I do here?
    } else{
                   //the property is undefined and returns ""
        "";
    };
}


    //check if a object has N levels of propertys
function checkNested(obj /*, level1, level2, ... levelN*/) {
  var args = Array.prototype.slice.call(arguments),
      obj = args.shift();

  for (var i = 0; i < args.length; i++) {
    if (!obj.hasOwnProperty(args[i])) {
      return false;
    }
    obj = obj[args[i]];
  }
  return true;
}

In the get_property method, how can I access the property if it does exist? I thought about having the object and its properties stored in an array like: object

params = ["user","name"]

but I cannot access them like this:

object.["user","name"]

Answer №1

Modify the get_property function by replacing the if statement with a for loop borrowed from the checkNested function. Instead of returning true or false, return the discovered value or an empty string "".

function get_property(obj){
    var args = Array.prototype.slice.call(arguments),
        obj = args.shift();

     // Incorporating a 'for' loop in place of the 'if' statement.
    for (var i = 0; i < args.length; i++) {
        if (!obj.hasOwnProperty(args[i])) {
          return "";   // Altered the output of this 'return' statement
        }
        obj = obj[args[i]];
    }
    return obj;  // Adjusted the result of this 'return' statement
}

No new logic was introduced, just a direct copy of your existing code with modifications to the return statements.

Answer №2

To reach your objective, you can follow this approach (without using the checkNested function):

//Parameters    {object, property1, property2, ... propertyN}
function retrieve_property(){
    var args = Array.prototype.slice.call(arguments),
       object = args.shift(),
       property = args.shift();

    if( object.hasOwnProperty(property) ){
        if( args.length > 0 ){
           //Invoke 'retrieve_property' with  {object[property1], property2, ... propertyN} , and so forth
           return retrieve_property.apply(retrieve_property, [object[property]].concat(args));
        }else{
           return object[property];
        }
    }else{
        return "";
    }
}​

Example:

var data = {
    "x" : {
        "y" : 8
    }
};

console.log( retrieve_property(data,"z") );        //  ""
console.log( retrieve_property(data,"x","y") );    //  8
console.log( retrieve_property(data,"x") );        //  {"y":8}

Answer №3

All you need is a straightforward recursive method.

function retrieve_value(object, property) {
    if (object[property]) {
        return object[property];
    }
    else {
        var result;
        for (var key in object) {
            if (object.hasOwnProperty(key)) {
                result = retrieve_value(object[key], property);
            }
        }
        if (!result) {
            // If we reach this point, it means the property doesn't exist at any level
            return;
        }
        else {
            return result;
        }
    }
}

Note: I initially misunderstood your query. Refer to @Engineer's response for accurate information. Leaving this here just in case it proves helpful.

Answer №4

Stop making things more complicated than they need to be. If you already know the structure of your object, simply access it like this:

obj['user']['name'];

If there's a possibility of undefined properties (which usually indicates a larger issue at hand):

let property;
try {
    property = obj.user.name;
} catch (error) {
    property = null;
}

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

Do not use the .map method! Caution: Every child component in a list must be assigned a unique "key" prop

I have recently started working with NEXT JS and I am encountering a peculiar issue for which I haven't been able to find a solution online. The warning message I'm getting is: "Each child in a list should have a unique key prop." Warning: Each c ...

Using useState to initialize a long value

Obtaining a very large state from JSON can be challenging, especially when it consists of at least 50 lines. During page generation, an error like "there is no such value" may occur if the initial value is not set and the interface is not assigned properl ...

Conceal the object, while revealing a void in its place

Is there a way to hide an image but keep the containing div blank with the same dimensions? I want it to appear as if no content was there, maintaining the original width and height. For example: http://jsfiddle.net/rJuWL/1/ After hiding, "Second!" appea ...

How to use multiple template urls in Angular 6

Currently, I am creating a front-end using Angular 6 and facing the challenge of having components with varying html structures based on the user who is logged in. The number of templates required can range from 2 to over 20, so my preference would be to ...

Error message: RefererNotAllowedMapError - Google Maps API has encountered an issue with

I've integrated the Google Places API into my website to display a list of addresses, but I'm encountering the error detailed below. Encountered the following error when trying to use Google Maps API: RefererNotAllowedMapError https://developers ...

Error: JQuery's on() function is not defined

After modifying the code in the original and changed code boxes, I'm now encountering an Uncaught Type error: Undefined is not a function. Any thoughts on why this might be happening? Thanks Original: $('.comment').click(function(e){ ...

Invoke a parent method from a nested child component in Vue

After setting up a project with vue-cli using the webpack template, I decided to incorporate a reusable bootstrap modal dialog in the App component. To achieve this, I created a method called showMessage in the App component that handles displaying the mod ...

Tips on when to display the "Email Confirmation" input text box only after updating the old email

Oh no!! Yes, that's exactly what I desire! I've been facing obstacles in trying to understand how to display the "Email Confirm" input text-box ONLY when the old email has been updated. Can someone point out where I might have gone wrong? :( ...

Can you explain the inner workings of the provided code in a step-by-step manner?

I stumbled upon this code snippet that checks if the number of occurrences of an element in an array is greater than a specified value, and if so, it will remove the number: function deleteNth(arr,x) { var cache = {}; return arr.filter(function(n) { ...

What are the best practices for utilizing ESM only npm packages alongside traditional npm packages within a single JavaScript file?

Hey there, I'm fairly new to web development and I encountered a problem when trying to require two packages, franc and langs, in my index.js file. It turns out that franc is now an ESM only package, requiring me to import it and mention type:module i ...

What is the process for aligning rows with the selected option from the drop-down menu

Alright, so here's the scenario: I have created a table along with two drop-down filters. The first filter is for selecting the Year, and it offers options like "All", "2023", "2022", and "2021". When I pick a specific year, let's say "2022", onl ...

Correcting the invalid syntax due to EOF issue

How can we resolve the end of file error? The brackets appear to be valid based on ecma standards, but it's not clear what is missing. After using jsonlint, this error was found: *Error: Parse error on line 16: ...States" }] }]}{ "i ...

Encountering a 500 server error while attempting to retrieve content from Google Images through the Web Speech API

My current project involves utilizing the Web Speech API to dynamically gather free images from Google. Here's how it works: I extract the search keyword using the Web Speech API in JavaScript. The keyword is then sent to the server (PHP) via an a ...

Experiencing a problem with my JavaScript code in Node.js due to an asynchronous issue arising when using a timeout

My goal with this code is to retrieve JSON questions and present them to the user through the terminal. The user has 5 seconds to respond to each question before the next one appears. However, I encountered an issue where the next question times out automa ...

Problems that seem to loop endlessly

I was working on some algorithm challenges from a coding platform, and I hit a roadblock with the "The Final Countdown" challenge. Here's what the challenge required: Provide 4 parameters (param1, param2, param3, param4), print the multiples of para ...

Guide to defining the encoding of an XML file with JavaScript

Hi there, I am currently facing an issue with encoding while creating a document using JavaScript. The problem is that the document rejects all non-ascii characters. For example, when passing the string "verificación", it gets replaced by "". Any suggesti ...

Utilize a callback function without any arguments, and make use of the

After working on tutorials from nodeschool.io, I encountered a challenging problem related to streams. The provided solution had me puzzled. I'm particularly confused about the role of the upper variable and why it's necessary to use this.push. ...

How can I import an excel spreadsheet using Javascript, or alternatively, convert an excel file to a text document

I have been updating my file upload page to handle both text and excel files. However, when trying to read excel files with my current code, I am getting strange output. It seems that my function, which was originally designed for text files, needs modific ...

Looking to sanitize an array of objects in Node.js? If you find that manually iterating through it only returns 'object Object', there are alternative methods to properly

I have a collection of items structured like this: var data = [ { msg: 'text' }, { src: 'pic.jpg',id: 21,title: 'ABC' } ]; My goal is to cleanse the values by manually iterating throug ...

Every time I attempt to execute mupx deploy, an error message appears

issue in console shubhabrata@shubhabrata-VirtualBox:~/Meteor/myapp$ mupx deploy Meteor Up: Advancing Meteor Deployments for Production Configuration file : mup.json Settings file : settings.json “ Discover Kadira! A powerful tool to monitor yo ...