ERROR: JSON - Cannot access property of undefined

My goal is to extract JSON values and create variables from them, but I keep encountering an error. Even when the JSON array is filled, I still face issues.

var tempArray = [];  
$("#sth td").each(function(){
    $this = $(this);
    tempArray.push({"COLOR":$this.attr("data-color"),});
});
console.log(JSON.stringify(tempArray));

if(tempArray != null) var color = tempArray[c-1].COLOR;

Can someone explain why I am getting this error in the last line:

Uncaught TypeError: Cannot read property 'COLOR' of undefined

Answer №1

Testing this in the console:

[]==null
> false

reveals that it returns false. Consequently, checking if an array equals null will always result in false, leading to the code inside the if statement being executed.

A better approach would be:

if(tempJS.length) var kolor=tempJS[c-1].COLOR;

There's no need for if(tempJS.length > 0) because any number is treated as true except for 0, which evaluates to false.

Answer №2

An empty array is distinct from null. You can check with if (arr.length > 0)...

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

I am looking to enhance my array of objects by implementing a filter. It is important that the filter does not allow for duplicate checkboxes with the

My website : On the left-hand side of my webpage, there is a set of checkboxes with some repeated names that I don't want. For example, "Rice" is repeated twice but I only want it to display once. When checking the Rice checkbox, it should show all c ...

How can we implement a select-all and deselect-all feature in Vue Element UI for a multi-select with filtering capability?

As a newcomer to VueJs, I am exploring how to create a component that enables multiple selection with a search option and the ability to select all or deselect all options. To achieve this functionality, I am utilizing the vue-element-ui library. You can ...

Prevent the function from being triggered repeatedly while scrolling

When a user scrolls to the bottom of the page, the following code is meant to load the next page. However, there are instances where it repeats itself due to rapid scrolling or while the AJAX content is still loading. Is there a way to prevent this code f ...

Converting and compressing JSON with GSON

Currently, I am focused on breaking down a SignalK JSON object into distinct canonical JSON items that accurately represent each individual value. The initial JSON structure is as follows: { "mmsi": "urn:mrn:signalk:uuid:5377770-4ee4-4a4b-3230-8880373320 ...

Is Node.js or Express.js a server-side language like PHP or something completely different?

Hello, I have a question about Node.js and Express.js. I come from a PHP background and understand that PHP operations and functions execute on the server and return results to the client's screen. In simple terms, does Node.js/Express.js serve the s ...

Invoking a function of a Redux-form React component

Is there a way to access the component method of a redux-form? I want my upload button to submit the form and also open the file select dialog if the user hasn't selected any file. Here is my code: UploadModal.js import React from 'react&apos ...

Numerous status buttons with a variety of background colors

There are 3 buttons on the order page: [New Order], [Processing], and [Completed]. When the processing button is clicked, the background of the button should change and the order status will be updated in the database. The [New Order] button will have a ...

Sorting through names within a nested array based on specific criteria

I have been struggling to filter by item name for the past day and haven't been successful. The issue lies in my attempt to use a sample array for filtering. While I am able to filter by category successfully, the same cannot be said for filtering by ...

Leveraging a service variable in Angular

Is there a way to access data shared in a service within a directive? Let's say we have a directive called resultsDirective, and a service named dataService. How can we retrieve a variable from the service within the directive? angular.module("someMo ...

The setState function in React is not being updated within the callback function

I've encountered an issue while working on a project in React. The puzzling part is why the variable selectedRow remains null even after using the setSelectedRow function inside the onClick callback. Despite my efforts to log it, the value always retu ...

Leveraging Cheerio in Node.js to locate a precise value within an option tag

I'm facing difficulties in selecting the exact number (in this case 7) which is the value of the option. This is what I'm attempting: var $ = cheerio.load(html); console.log($('ProductSelect').val($("option:contains('7')").v ...

Is there a way to reverse the animation playback in Angular?

I am working on an animation that involves a box fading from its original color to yellow. However, I would like to achieve the opposite effect: when the page loads, I want the box to start off as yellow and then fade back to its original color. The challe ...

losing track of the requested parameters while working asynchronously with Firestore documents

Today is my first time experimenting with firestore and express. Here is the code snippet I am using: app.post('/api/create', (req, res) => { (async () => { try { console.log(req.body); //the above consle.lo ...

Ways to prevent scrolling in Angular 6 when no content is available

I am developing an angular 6 application where I have scrollable divs containing: HTML: <button class="lefty paddle" id="left-button"> PREVIOUS </button> <div class="container"> <div class="inner" style="background:red">< ...

Issue with Camera inversion not functioning properly in THREE.js with 1 Renderer and 2 Viewports

Check out this JSFiddle example In my project, I have a single scene with two cameras. Each camera is assigned to its viewport, and both viewports are placed side by side on the same renderer object. My goal is to have the second camera display a mirrore ...

Tips for testing the JsonProcessingException scenario in Junit testing

In the service class I have, there is one implementation method where an ObjectMapper is locally created to write data like this: public class MyService{ public void myMethod(){ try{ ObjectMapper objectMapper = new ObjectMapper(); objectMapper.writeValueAs ...

Typehead.js on Twitter is displaying the full query instead of just the value

The Problem This is the issue I am facing with my code. My goal is to retrieve only the value, but instead of that, the entire query value is being returned. var engine; engine = new Bloodhound({ local: [{value: 'red'}, {value: 'blue&apo ...

Is there a way to identify if the parent page has completed loading while within an iframe?

Is there a way to detect properties or events within the iframe that can help determine this? The src of the iframe and the parent page belong to different domains. ...

Trigger the ASP .NET OnCheckedChange server event using JavaScript

One issue I encountered is related to a checkbox with an OnCheckedChanged event. Occasionally, I modify the checked status of the checkbox using javascript. However, when this occurs, the OnCheckedChanged event does not trigger. Is there any method to ens ...

Highlighting text in React using hover effects on list elements

Imagine having HTML / JSX structured like this: <ul> <li>First point in list</li> <li>Second point in list</li> </ul> and the goal is to highlight a contiguous range that spans multiple list items: <ul> < ...