Converting JSON information into a JavaScript array

var test=[];
$(document).ready(function(){
            $.getJSON("data.json",function(data){
                $.each(data,function(key,value){
                    test.push(value.topic);
                });
            });
        });

I have written some javascript code to push all values of a json object with the key as topic into an array called test. However, when I try to access test[i] (where i is any integer within the array length), I receive an error saying "undefined". Can you help me figure out what I am missing?

Below is a sample of my json object:

[
        {
            "topic": "Books",
            "quantity": 3
        },
        {
            "topic": "Grossery",
            "quantity": 3
        },
        {
            "topic": "stationery",
            "quantity": 3
        },
        {
            "topic": "food",
            "quantity": 2
        },
        {
            "topic": "market items",
            "quantity": 3
        }
]

Answer №1

Check out this functional code example:

var items = [
        {
            "type": "Shoes",
            "quantity": 5
        },
        {
            "type": "Hats",
            "quantity": 2
        },
        {
            "type": "Gloves",
            "quantity": 3
        },
        {
            "type": "Socks",
            "quantity": 4
        },
        {
            "type": "Scarves",
            "quantity": 1
        }
]
var itemList = [];
$.each(items, (i, v) => itemList.push(v.type));
console.log(itemList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

Answer №2

It seems like your code is functioning correctly based on my testing.

Have you made sure not to access the data before the callback function you provide to getJson is executed?

Below is an example that runs successfully when served locally using python3 -m http.server 8080:

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
        <script>
            var test=[];
            $(document).ready(function(){
            $.getJSON("data.json",function(data){
                $.each(data,function(key,value){
                    test.push(value.topic);
                });
                // Make sure to only use the test array after the data has loaded
                doWork();
            });
        });
        function doWork() {
            $('#output').text(
                test + ' ' + test[0]
            );
        }
        </script>
    </head>
    <body>
        <div id="output"></div>
    </body>
</html>

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

Changing the size of an iframe and closing it by pressing the ESC

I am developing an application that requires the ability to resize an iframe. When the user clicks the "Full Screen" button, the iframe should expand to occupy the entire screen. The iframe should return to its original size when the user presses the "Es ...

Tips for validating updates in MongooseEnsuring data integrity is

My current Schema does not validate upon updating. Can you please point out where I went wrong and help me fix it? ...

Updating MongoDB collections in Mongoose with varying numbers of fields: A step-by-step guide

Updating a mongodb collection can be challenging when you don't know which fields will be updated. For instance, if a user updates different pieces of information on various pages, the fields being updated may vary each time. Here is my current appro ...

Error encountered: The Jquery-ui functionality ceases to operate upon the completion of content

I'm utilizing the jQuery UI library to rearrange the items on my list. Initially, everything works smoothly without any issues. However, when I navigate to another page and then return to the page with my list, I encounter difficulties. It's wor ...

I need help with a process to extract information from a database and convert it into an object specifically for my situation

Currently, I am utilizing the postgres row_to_json function to retrieve data that has been stored using JSON.stringify(). However, upon retrieval and attempting to parse it with JSON.parse(), an error message stating "unexpected token ," is returned. The ...

The initialization process removes the 'const' qualifier from the target type of the pointer

Hey there! I'm struggling with sorting an array of structs containing char names alphabetically using qsort. However, I keep encountering an error message that says "initialization discards ‘const’ qualifier from pointer target type". I'm pre ...

Mapping JSONP responses for jQuery UI autocomplete

Attempting to implement jqueryUI autocomplete. After alerting the response, it shows: ([ { "id": "test", "label": "test", "value": "test" } ]); However, when trying to map the result, the dropdown remains empty. Here is the code being used: <script> ...

Can an older style class be inherited from an ECMAScript 6 class in JavaScript?

When I run the code below on Node.js version 4.2.1: 'use strict'; var util = require('util'); class MyClass { constructor(name) { this.name = name; } } function MyDerived() { MyClass.call(this, 'MyDerived'); } ...

Jasmine and Karma encountered a TypeError stating that the function this.role.toLowerCase is not valid

Currently, I am in the process of writing a test case for a page within an application that our team is actively developing. However, I have encountered a challenging error within one of the test cases that I am struggling to overcome. Below is my Spec fil ...

Deactivate PyV8's automatic garbage collection functionality

I am currently experiencing an issue that appears to be stemming from the interaction between Python and PyV8's garbage collection processes. To temporarily address this problem, I have disabled Python's garbage collection and implemented a worka ...

The elusive Ajax seems to be slipping through our grasp,

I am currently working on a website app to display the availability of PCs in my University using JSON data from the University website and AJAX. I am facing an issue where it shows all the MACs for the first room, but returns undefined for others. Since t ...

What is a method for saving a file from Chrome to a network drive using scripting language, even though it's currently functioning in IE?

In a SharePoint 2013 document library, I have implemented a JavaScript function that captures user access to files. The function creates a .txt file containing information about the user ID, username, and file path, which is then saved to a network drive l ...

Exploring the variance in outcomes when directly accessing an AuthService state versus utilizing a function in a React AuthContext

I am currently working on creating an AuthContext, but I am encountering an issue with changing the state of a variable. Here is the code snippet: index.js import Head from "next/head"; import Image from "next/image"; import styles fro ...

Every time I attempt to add data to the database, I am encountering the issue of receiving 'undefined' values for every row

I'm struggling to save the JSON array returned by my output to a database in Node.js. Whenever I attempt to insert it into the database, all rows display 'undefined' values. What other options can I explore? I also need the output as a JSON ...

Utilize Node JS to assign variables to HTML form inputs

Can anyone help me with storing HTML form inputs in variables using Node JS? I'm having trouble getting it to work properly. Below is the HTML form snippet: <form action="localhost:8080/api/aa" method="post"> <input id="host" type="text ...

Unable to perform updates for personalized fonts

I've been trying to incorporate custom fonts into my website, but I seem to be facing difficulties in actually implementing them. Could someone please let me know if I am doing it correctly? .pattern{ background:rgba(0,0,0,.5) url(../images/pattern ...

Steps for connecting an external .otf file in p5.js

I'm struggling to connect a custom font file to my p5.js sketch through a URL in order to upload it on codepen.io. Unfortunately, the font is not available on Google Fonts. I attempted to include the URL in the load font function like this: loadFon ...

Tips on accessing the v-model value with a parameter in VUE

Looking to access the v-model value using a parameter, I attempted the following code: <template> <div v-for="(item, idx) in data"> <input :id="item" :v-model="item"></input> <button @click=&q ...

Coordinating Angular to communicate with Node.js to send and receive data

I am currently working on a project using express.js, but I would like to integrate angular into the project to create a single page application. The website currently refreshes the entire content from the server whenever a link is clicked, which seems ine ...

Creating new Vue components is happening towards the end of the loop

I am currently encountering an issue with my Vue components. I have structured them in a hierarchy where I have a post-index component displaying all posts, containing a post-view component for individual posts, and within that, a post-like component to ha ...