Issue with recursive function failing to accurately assess object keys

I am facing an issue with two objects that have identical length and keys, but different values. The problem lies in a method designed to evaluate these objects, which is currently breaking down. I've spent hours trying to troubleshoot this issue.

Below is the content of originalReference:

{  
   "id":68,
   "article_id":12338,
   // Other key-value pairs...
}

And here is the content of reference:

{  
   "id":68,
   "article_id":12338,
   // Other key-value pairs...
}

In comparing the two objects, I noticed that articleTitle in originalReference contains typos, while it is correct in reference.

The intended function should prevent overwriting values in originalReference if they are non-empty or defined. However, there seems to be an error occurring that reads:

TypeError: Cannot read property 'articleTitle' of undefined
, even though both properties are clearly defined.

Here is the function in question:

evaluateEmptyValues: function(reference, originalReference) {
    var vm = this;

    // Logic for evaluating empty values

}

Answer №1

Is it more appropriate to adjust your code in this way?

if (reference[prop] != undefined && reference[prop] != null) {

rather than using an OR condition like before:

if (reference[prop] != undefined || reference[prop] != null) {

Answer №2

Managed to make it work with the following code:

handleEmptyValues: function(reference, originalReference) {
    var self = this;

    // Retrieve keys and values from both reference objects
    var referenceLength = Object.entries(reference).length;
    var originalReferenceLength = Object.entries(originalReference).length;

    if (referenceLength === originalReferenceLength) {
        try {
            for (var key in reference) {
                if (reference[key] !== undefined || reference[key] !== null) {
                    if (typeof (reference[key]) === 'string' && reference[key].trim() === '') {
                        reference[key] = originalReference[key];
                    }

                    if (typeof(reference[key]) === 'object' && typeof(originalReference[key]) === 'object') {
                        var innerObjLength = Object.keys(reference[key]).length;
                        for (var nestedKey in reference[key]) {
                            if (originalReference[key][nestedKey] !== undefined) {
                                if (originalReference[key][nestedKey] !== null) {
                                    for (var i = 0; i < nestedKey.length; i++) {
                                        if ((reference[key][nestedKey] === null || reference[key][nestedKey] === '') &&
                                            originalReference[key][nestedKey] !== null) {
                                            reference[key][nestedKey] = originalReference[key][nestedKey];
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (Array.isArray(reference[key]) && Array.isArray(originalReference[key])) {
                        reference[key].forEach((item, index) => self.handleEmptyValues(item, originalReference[key][index]));
                    }
                } else {
                    if (originalReference[key] !== undefined) {
                        if (originalReference[key] !== null) {
                            reference[key] = originalReference[key];
                        }
                    }
                }
            }
        } catch(error) {
            console.log(error);
        }
    }
},

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

Error: The functionXXX is missing and cannot be found when HTMLInputElement is clicked

During my selenium automation test, I encountered an issue with a remote webdriver while trying to launch an HTML file. Although the HTML page opened correctly, an error occurred when attempting to click on a submit button that calls a javascript function ...

Most efficient method for updating ASP.NET page with Javascript

I am currently working on a project in ASP.net where I have to handle a large number of questions stored in XML format. My first challenge was to render these questions dynamically on a web page using RadioButtonLists and a placeholder called sectionHolder ...

Create a dynamic onClick event script and integrate it into Google Optimize

I need to incorporate a button element into my website using Google Optimize for an experiment. This button needs to trigger a specific script depending on the variation of the experiment. I have attempted two different methods: <button id="my-button" ...

Error in Node.js: Trying to access property 'get' of an undefined object

Although I have some knowledge of JavaScript, I am new to Node.js. Despite it being a common issue, I am having trouble identifying the source of the error because my debugging skills in Node.js are lacking. Here is my app.js: var index = require('. ...

What are the benefits of using Bower.js when npm is already functioning well?

When working in the main project directory, running the command npm init will create a file called "package.json". If I need to install dependencies such as angular, jQuery and bootstrap, I can use the following commands: npm install angular --save-de ...

The functionality of the Angular ng-bind-html directive may be unreliable in specific scenarios

I've exhausted all the solutions found on stack overflow but still haven't found a solution. Using angular 1.4.4 and ng-repeat directive, I am attempting to display a HTML comment inside a table row. A sample comment looks like 'Test commen ...

Exploring the wonders of Node.js, Redis, and Express.js while navigating through the enchanting world of Asynchronous

Hello there, I must confess that this is a whole new realm for me... Here is what we've got: app.get('/user/:user_id/followings', function(req, res) { var response = {} , userId = req.params.user_id , ids = req.param(' ...

If the given response `resp` can be parsed as JSON, then the function `$

I was using this script to check if the server's response data is in JSON format: try { json = $.parseJSON(resp); } catch (error) { json = null; } if (json) { // } else { // } However, I noticed that it returns true when 'res ...

"PHP Dilemma: Navigating the Ajax Button Press Situation

I've been attempting to create a button that triggers a PHP script on a webpage and updates only a specific div tag, but so far I haven't had any success. Removing the $ajax section of the script allows my buttons to change states, but as soon as ...

Using Node.js and Less to dynamically select a stylesheet source depending on the subdomain

Currently, my tech stack consists of nodejs, express, jade, and less. I have set up routing to different subdomains (for example: college1.domain.com, college2.domain.com). Each college has its own unique stylesheet. I am looking for a way to selectively ...

Retrieving Specific Node Value in Array From XML Document

In my JavaScript function, I have a variable named "result". The value of the variable "result" is an XML. I need to create an array containing only the values of the opportunityid (highlighted in the image). How can I extract the particular node value ...

Updating deeply nested document in Mongoose

Is it possible to change the value of array1.array2.status, according to the schema provided below? const SomeSchema = new mongoose.Schema({ status: Boolean, array1: [{ array2[{ status: boolean }] }] }) ...

Utilizing jQuery to display labels only for selected checkboxes while concealing the ones that are not checked

I currently have the following setup: <style>.selectit{display:none;}</style> <div id="foo"> <label class="selectit"> <input type="checkbox" name="one" id="one" checked> One </label> <label class="selectit"> <i ...

Having trouble with ES6 in Canvas - why won't my code display correctly?

I'm currently working on developing a painting app using ES6. However, I'm facing issues with the positioning and line drawing on the canvas. The lines are not being drawn in the correct position; for example, the top-left corner is formed when ...

Is it possible to rotate a Three.js group around a specific point within the group using Three.js?

Summary: The objective is to adjust the arrow's orientation around the circle. We have a function that introduces a shape (https://i.sstatic.net/l3lZB.jpg) (comprising of three Meshes) into the scene. By default, it points to the right, but we desire ...

Allow Vue to handle the registration of the datepicker event

Is there a way to notify Vue when the datepicker changes the selected date? new Vue({ el: '#app', data: { termin: '' }, computed: { }, methods: { } }) This is just an input field: <div id="app"> <div c ...

ESLint does not recognize the components used in Element UI

I've been working with Vue.js and Element UI components. However, when I try to use elements like Input or Col, ESLint throws an error with the message invalid-end-tag. I have already added eslint-plugin-vue to my setup, so why isn't ESLint reco ...

Retrieving titles based on a particular id or class

After searching for a Jquery automatic table of content generator, I finally came across this one that works perfectly. $(document).ready(function() { $(tocList).empty(); var prevH2Item = null; var prevH2List = null; ...

Manipulating binary data through the use of encodeURIComponent

Currently, I am reading a binary file by making a jQuery ajax get request. The file (a zip file in this instance) is returned as a string. After performing some actions on the file within the browser without modifying it, I need to send it back to a server ...

From mongoose to swagger: "<field>" validation error - BSONTypeError: The argument provided must be a string containing either 12 bytes or 24 hexadecimal characters

I'm currently working on developing a REST API using Express, Mongoose, and Swagger for API documentation. To automate the process of converting my existing schema to Swagger, I utilized the mongoose-to-swagger package. However, I encountered an issue ...