No data appears to be populating the Javascript data list, yet no errors are being displayed in

I'm facing an issue where I have data that I'm using to create two arrays, but they both end up empty without any errors in the console.

Below is the data:

mydata = {
    "id": "661",
    "name": "some name",
    "description": "some desc",
    "subcat": {
        "662": {
            "id": "662",
            "name": "sub 1",
            "translations": null
        },
        "663": {
            "id": "663",
            "name": "sub 2",
            "translations": null
        }
    },
    "image": null
};

Here is the code snippet:

chList=[];
thList=[];
thCount=[];

for (var i = 0; i < mydata.length; i++) {

    var obj = mydata[i];

    var cl = obj.name;

    if (obj.subcat != null) {
        chList.push(cl);
    }

    if(obj.subcat) {

        if (i < 10) {

            var nme = obj.subcat.map( function(item){
                return item.name;
                console.log(nme);
            });

            thList = thList.concat(nme);
            thCount.push(nme.length);
        }

    }

}

console.log(thList);
console.log(thCount);

The issue here is that both thList and thCount end up empty as shown: []

What can be done to fix this problem?

Answer №1

To determine the length of the data stored in mydata, you can utilize the Object.keys method.

var length = Object.keys(mydata);

Answer №2

mydata.length is not defined because you are attempting to access the length property, which does not exist on the Object myData. Due to this, the loop iteration does not work and as a result, your arrays thList , thCount remain empty.

In Javascript, the length property exists on Arrays. If you try to access a property that is not part of the object, Javascript will return undefined

If you want to access the properties of the object, you can iterate over the enumerable properties like this:

for (var property in mydata ) {
    if (mydata.hasOwnProperty(property)) {
        // Your code here
    }
}

Additionally, the statement var obj = mydata[i]; will not work in this case because mydata is not an array. If you define mydata as an array, then the statement var obj = mydata[i]; will work as expected.

Answer №3

It appears that your assumption is that mydata should contain an array of objects, rather than just a single object as shown. To optimize your code, consider wrapping the single object presented for mydata inside an array, and possibly adding similar objects to it.

Furthermore, the line obj.subcat.map will not function as intended since subcat is not an array. Instead, you should utilize map with Object.keys(obj.subcat) to access obj.subcat using the keys obtained.

By making these two adjustments, your code can function correctly:

// mydata should be an array
mydata = [{
    "id": "661",
    "name": "some name",
    "description": "some desc",
    "subcat": {
        "662": {
            "id": "662",
            "name": "sub 1",
            "translations": null
        },
        "663": {
            "id": "663",
            "name": "sub 2",
            "translations": null
        }
    },
    "image": null
}];

var chList=[];
var thList=[];
var thCount=[];

for (var i = 0; i < mydata.length; i++) {
    var obj = mydata[i];
    var cl = obj.name;
    if (obj.subcat != null) {
        chList.push(cl);
    }
    if(obj.subcat) {
        if (i < 10) {
            // You need to use Object.keys to iterate over an object
            var nme = Object.keys(obj.subcat).map( function(key){
                var item = obj.subcat[key]; // retrieve item by key
                return item.name;
                // Note: console.log after `return` will not execute
            });
            thList = thList.concat(nme);
            // Consider repeating 'nme.length' times:
            thCount = thCount.concat(Array(nme.length).fill(nme.length));
        }
    }
}

console.log(thList);
console.log(thCount);

Answer №4

Consider attempting the following approach.

for (let item in customobject) {
    // retrieve your information in this manner 
    customobject[item].anything
}

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

Complete and automatically submit a form in a view using AngularJS

I have developed a basic AngularJS application that is functioning smoothly. Currently, I am looking to populate certain fields and submit the form directly from the view without requiring any user input. Below, you'll find some simplified JavaScrip ...

Using local storage with github sites can lead to some unexpected and peculiar behavior

Currently, I am working on a simple clicker game using HTML and JavaScript. To store the variables money and taxCollecters, I have implemented local storage. However, I am encountering strange issues when trying to use the save and load buttons on the Gi ...

Displaying XML data using d3js

Currently, I am working on a d3.js assignment for my school project. While looking at some examples to load an XML file, I seem to be encountering difficulties in figuring out what's going wrong. The XML file is loading correctly, but as I am still le ...

Javascript puzzle - I have 99 obstacles

...but a malfunction isn't one. Hey there, I am new to learning so I apologize for the seemingly simple question. I'm experimenting with a theoretical logic statement that would work using javascript. For instance: if (issues == 99) { malfunct ...

Switching players every two turns in a JavaScript AngularJS game

I have implemented an AngularJS score keeping game where players switch every two turns. The code works for one round, but I want to create a loop that keeps switching players. Check out my code below: app.controller('EventController', function( ...

What is the best way to eliminate all click event handlers with jQuery?

I'm encountering an issue where multiple click events are being attached to a button. Specifically, when a user clicks on an 'Edit' link, the following JQuery code is executed: $("#saveBtn").click(function () { saveQuestion(id); }); Ea ...

Tips for effectively utilizing the useDraggable and useSortable hooks within the dnd-kit library

I'm currently working on developing a basic calculator using React and dnd-kit. The idea is to have draggable elements in the calculator that can be sorted within a droppable area with smooth animation effects. However, I've encountered an issue ...

Is it possible to integrate Processing JS on top of an HTML element?

I have currently integrated Processing JS with the HTML canvas element on a website. The goal is to have the Processing JS animation run smoothly over the existing HTML elements on the page. You can check out the site at [usandthings.com][1] to get an idea ...

Is it possible to perform a local multipleSearch programmatically using free-jqgrid?

Despite spending countless hours and even days searching, I have yet to find a satisfactory solution to my dilemma: All I desire is to utilize the local search/filter capabilities of jqgrid (currently using free-jqgrid 4.9.0) programmatically. I am hopin ...

using JQuery, add a class on click event or on page load

Solved It! After encountering a problem created by some sloppy moves on my part, I managed to solve it. However, another issue arose: adding the class current to li with data-tab="tab-1 upon page load. $('ul.tabs li').click(function(){ ...

Issue with Select2: When using a remote select2 control, the tab key press does not allow for the selection of the highlighted

I have set up select2 to load ajax data into select2 based on the example provided in this link Load ajax data into select2. In the example, I can type text, use arrow keys to navigate, and then hit tab to select the highlighted item. However, in my case, ...

Hierarchy-based dynamic breadcrumbs incorporating different sections of the webpage

Currently in the process of developing a dynamic breadcrumb plugin with either jQuery or Javascript, however I am struggling to implement functionality that allows it to change dynamically as the page is scrolled. The goal is to have a fixed header elemen ...

How do webpack imports behave within a ReactJS project?

In my ReactJS project, I have utilized various 3rd party libraries such as lodash, d3, and more. Interestingly, I recently discovered that I did not explicitly write imports like import d3 from 'd3' or import _ from 'lodash' in all of ...

Guide on importing npm packages without TypeScript definitions while still enabling IDE to provide intelligent code completion features

I am currently utilizing an npm package that lacks type definitions for TypeScript. Specifically, I'm working with the react-google-maps library. Following their recommended approach, I have imported the following components from the package: import ...

Having trouble with JavaScript not functioning correctly within the Update Panel?

Does anyone know how to include JavaScript from a remote source inside an update panel? I'm trying to add Facebook and Twitter share buttons to my application. Here is the code snippet: The problem is that this code works fine when the page is initia ...

The appearance of an unforeseen * symbol caused a

Having issues with this particular line of code, import * as posenet from '@tensorflow-models/posenet' The error 'Uncaught SyntaxError: Unexpected token *' keeps popping up, I have the latest version of Chrome installed and I've ...

React - the elusive nature of variable mutation

In my React app, there is a requirement to choose a specific version of a phone and then confirm the selection. Below is an excerpt from the React component's code: const App = () => { const [selectedVersion, setSelectedVersion] = useState(""); ...

Ways to implement variable face sizes in three.js meshes

Recently, I dove into the world of three.js and started playing around with it. I've been pondering whether there's a way to add some randomness to the size of the faces in a mesh created from their existing geometries. While three.js is fantast ...

What is the process for incorporating an npm package into an HTML document?

Here is the code from my HTML file: <!DOCTYPE html> <head> ... </head> <body> ... <script src="script.js"></script> </body> This is what I have in my JavaScript file named script.js: import * as File ...

Mongoose: Unable to fetch item using its specific identification - Error 404

I've been attempting to fetch objects from MongoDB using Mongoose, but I keep encountering a 404 error. router.get('/blogs/:id', function(req, res){ console.log('trying to get one blog post by id'); Blog.findOne({ _id: req.para ...