Ensure all keys in a Javascript JSON object are checked for undefined or null values, and assign default values if necessary

After just two days of learning JavaScript, I find myself a bit ahead of the game in what I'm trying to accomplish. I have a JSON array that I use to update content on my webpage. However, I've encountered a problem where if an empty ('null') key is encountered, the process halts completely.

document.getElementById("id1")src=json.img1.link;
document.getElementById("id2")src=json.img2.link;
document.getElementById("id3")src=json.img3.link;

For example, if json.img2.link is empty, JavaScript will not only skip replacing "id2" but also won't replace "id3".

Now, I'm exploring ways to handle this issue, perhaps by setting a default value if nothing else.

Answer №1

The code is halting its execution due to an error - attempting to access the property link of an object that is undefined

To resolve this issue, consider using

document.getElementById('id2').src = json.img2 ? json.img2.link : 'defaultLink';

By implementing this, you are verifying if img2 is undefined (null) and providing a default value. This logic assumes that the undefined object is img2.

Answer №2

I have a different perspective on your code. It seems to have an issue since you are missing the period before the src. Here's a suggestion:

document.getElementById("id1").src = json.img1.link;
document.getElementById("id2").src = json.img2.link;
document.getElementById("id3").src = json.img3.link;

If that doesn't resolve the problem, please inform us.

By the way, I appreciate your effort in learning JavaScript rather than jumping straight into jQuery! Keep up the good work!

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

Leverage IBM Worklight to initiate iOS native code execution upon plugin creation

Currently, I am working on integrating iOS Native code into my Worklight application. I have successfully developed a Cordova plug-in with the following code: HelloWorldPlugin.h #import <Foundation/Foundation.h> #import <Cordova/CDV.h; @interf ...

Generating output from a callback function in TypeScript

When I execute a graphql query, the showUsers function is supposed to display all users (styled as boxes). However, at the moment, nothing is showing up. I am utilizing a functional component instead of a class component. This function is invoked after m ...

Ways to automatically run Java script again when new elements are included in the document model

Recently, I added paging and filtering to a page displaying a list of products. @model ProductFiltersViewModel ... <div class="row"> <aside class="col-3"> <nav class="sidebar card py-2 mb-4"> ...

Guide on processing a hefty JSON file by rounding decimals to the nearest integer and calculating the average of y values when there are duplicate x values

I am currently exploring ways to efficiently filter and parse through extensive JSON data sets. My main goal is to round the x values to the nearest integer. In cases where there are duplicate entries, I aim to calculate the average of the y values while ...

Steer clear of using the character sequence "&#8220;" in both PHP and

I am struggling with the encoding (I think). A script I wrote fetches a PHP file through AJAX that generates a JSON file. The JSON file appears as follows in Firebug: ["&#8220;This is a word&#8221; This not"] I am trying to find a way to remove & ...

What is the best way to modify specific properties within a JSON file that contains nested data without altering its overall structure?

Here's how my JSON file is structured: { "Logging": { "LogLevel": { "Default": "Information", "Microsoft.Hosting.Lifetime": "Information" } }, ...

Utilizing AES encryption in C# and decrypting it in Angular, converting it from a byte[] / number array with the help

I am looking to securely encrypt and decrypt a byte[] in a C# API endpoint, then convert the decrypted document to base64 for viewing in a PDF viewer within an Angular 14 app. I came across this helpful guide on Stack Overflow [https://stackoverflow.com/q ...

What could be the reason for my Bootstrap popover malfunctioning?

I've been attempting to incorporate the Bootstrap popover into my project. I copied the code exactly from the example provided on the website, but unfortunately, it doesn't seem to be functioning properly on my site. Below is the full code snippe ...

`Combining Promises and yields for seamless functionality`

I have been struggling to incorporate yield with a created Promise. Despite extensively researching, I am still unable to understand where I am going wrong in my implementation. Based on my understanding, when calling the generator function, I need to use ...

Generating interactive charts using JSON data parsed from MySQL database for Highcharts visualization

Just starting out and feeling (almost) desperate. My goal is to: Read temperature data from a sensor (working, returns float) Save the data in a MySQL database table called boxklima.sensorid (working - table name: boxklima.0414604605ff) as sets of date-t ...

I am attempting to build a party planning website but I am encountering an issue where the output is not generating properly. Whenever I click on the submit button, the information I input

I am struggling to create a party planner website and encountering issues with the output. Whenever I click on the submit button, the form just clears out without any feedback or result. Here is what the expected output should be: Validate event date 1: ...

What is the best approach to eliminate the 'false' type within a setState function in React?

Hey, I've been working on a project that involves using the useState hook and dealing with state using generics. I encountered an issue where I manipulated a fetched array within a setState function using the filter method, which resulted in returnin ...

Unable to display child component using VueRouter

Recently, I started delving into VueJS and decided to create a new Vue application using vue-cli. After making a few modifications, this is what my router.js looks like: import Vue from 'vue' import Router from 'vue-router' import Hell ...

Determining Velocity of an Object in Three.js

Can anyone help me figure out how to calculate an object's velocity in three.js? I've checked the Object3D documentation but can't seem to find anything related to velocity. Appreciate any assistance, ...

Using numerous modal windows within the .map function

I am working with a .map function and I want to create a modal in each div generated by the .map. return ( {this.state.DataBook.map(function (item, i) { return ( <div> <Button color="danger" onClick={this.toggleModal}>test Mo ...

Is it possible to display all tabs simultaneously with jQuery for tabbed content?

I'm currently utilizing jQuery to organize my content into various tabs, and it's working perfectly for displaying a specific <div> when a tab is clicked. However, I'm now looking to add a button that can toggle the display of all tab ...

Decoding JSON to create a Ruby iterator

I have a JSON file containing parsed data stored in the @colors instance variable. Here is an example of the data: [{:color=>"red", :value=>"#f00"} {:color=>"green", :value=>"#0f0"} {:color=>"blue", :value=>"#00f"} {:color=>"cyan", :v ...

When the down key is pressed in a textarea, choose the list item

I have HTML similar to the following <div class="row"> <textarea id="txtArea" ng-model="input" ng-change="handleOnChange(input);getSearchField(input);" ng-click="search(input)" ng-focus="search(input);" ...

Continuously tapping on overlapping slides

I encountered an issue where the slide that I set the opacity to 0 on is still clickable, despite setting pointer events to none. In my slideshow, consisting of 2 slides, clicking on the first slide redirects me to the hyperlink of the second slide. Chec ...

What is the best way to create reusable Javascript code?

Lately, I've adopted a new approach of encapsulating my functions within Objects like this: var Search = { carSearch: function(color) { }, peopleSearch: function(name) { }, ... } While this method greatly improves readability, the challeng ...