Objects that are included into an array will end up with an undefined value

Currently, I am in the process of coding a command for my Discord bot that involves adding items to an array of objects stored within a JSON file. To achieve this functionality, I have implemented the following code snippet:

let rawdata = fs.readFileSync('config.json');
let blacklist = JSON.parse(rawdata);

var newWord = {"word": args[3], "count": 0}
blacklist.words.push(newWord);

let data = JSON.stringify(blacklist);
fs.writeFileSync('config.json', data);

Essentially, what this code does is extract the fourth word from the command (args[3]), encapsulates it within an object (

{"word": args[3], "count": 0}
), and then appends it to the existing list of objects housed in the JSON file. While this setup functions as intended, upon attempting to retrieve this list of objects, those added by the bot are coming back as undefined.

The JSON structure within the file is outlined below:

{"words":[{"string":"test","count":0},{"word":"abc","count":0}]}

While the initial object within the list

{"string":"test","count":0}
was manually inserted during the file's creation, the subsequent object
{"word":"abc","count":0}
was incorporated by the bot.

Below is the provided code snippet utilized to access the list of objects:

var words = ""
for (i = 0; i < blacklist.words.length; i++) {
    words += "- " + blacklist.words[i].string + "\n";
    console.log(blacklist.words[i].string);
}
message.reply("here are the words in your blacklist:\n" + words);

Upon execution, the output yielded: https://i.stack.imgur.com/Nwh6E.png

Given my novice understanding of JavaScript and grappling with its asynchronous nature, my suspicion is that there may be a critical error in my approach.

Answer №1

Upon close inspection, it becomes evident that your JSON generated file contains two distinct keys: string and word. Currently, only the value of string, which is test, is visible while the other object lacks the key for string.

To resolve this issue, you have two options: 1. modify the keys to match each other or 2. utilize both keys using inline if/else statements.

for (i = 0; i < blacklist.words.length; i++) {
    words += "- " + blacklist.words[i].string + "\n";
    console.log(blacklist.words[i].string || blacklist.words[i].word);

}

Answer №2

for (j = 0; j < blacklist.words.length; j++) {
    words += "- " + blacklist.words[j].name + "\n";
    console.log(blacklist.words[j].name);
}

this snippet is aiming to access the name key in the words array of the blacklist object. Be sure to double check the key of the 2nd element in your JSON file as it may not be named 'name'.

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

Checking the Value of the Second Child Element Using jQuery

I am struggling with a DIV structure that looks like this: <div class="metafield_table"> <div class="metafield"></div> <div class="metafield"></div> <div class="metafield"> ...

What is the significance of property placement in a Mongo query: at the beginning versus at the

Currently, I am in the process of creating a query to retrieve data from the mango collection. Interestingly, I have written the same query in two different ways. Here is my working query: db.getCollection('routes').find({"routes.routeId": "r1q ...

The touch event doesn't seem to be functioning properly on the div element, but it works perfectly on the window element

I have a dilemma that's been puzzling me lately. I'm trying to append a touchevent to a div, but my current method doesn't seem to be working. Here's what I've tried: $("#superContainer").bind('touchstart', function(even ...

Select a single radio button containing values that can change dynamically

<input type="radio" on-click="checkDefaultLanguage" id="checkbox" > [[names(name)]] This custom radio input field contains dynamic values and I am attempting to create a functionality where only one radio button can be selected at a time while dese ...

Another component's Angular event emitter is causing confusion with that of a different component

INTRODUCTION In my project, I have created two components: image-input-single and a test container. The image-input-single component is a "dumb" component that simplifies the process of selecting an image, compressing it, and retrieving its URL. The Type ...

Obtain data from jQuery Data row

I am currently working on an asp.net page where I have implemented jQuery datatables. Below is a snippet of the code: <% foreach (SubmissionSearchResult result in SearchResults) {%> <tr data-name='<%=result.ID %>'> For each r ...

Is there a way for me to access this user's data with just a click?

When selecting a user from the list, more information should be displayed on the right. However, currently, a random user is being shown. Should I retrieve its index and compare them? Assistance is needed to clarify this issue and locate the necessary info ...

Updating JSON files from CI variables in Visual Studio Team Services is crucial for maintaining consistency and accuracy

Visual Studio Team Services offers the ability to modify web.config appSetting parameters using values specified in variables. You can find more information on this process here. However, is there a similar method to update a json file? ...

Steps for dynamically changing the class of a dropdown when an option is selected:

Check out this code snippet : <select class="dd-select" name="UM_Status_Engraving" id="UM_Status_Engraving" onchange="colourFunction(this)"> <option class="dd-select" value="SELECT">SELECT</option> <option class="dd-ok" value= ...

What is preventing me from passing a JSON array as data in a GET request using jQuery Ajax?

When sending a get request like the one below: $.ajax({ url: 'http://localhost:8000/api/points/', contentType:"application/json", dataType: "json", data: JSON.stringify({"content_type":content_type,"object_id":object_id}), t ...

Utilize the dropdown menu to load JSON data and dynamically update the content of a div section on a website

I have been struggling to find a way to load JSON data from a drop down menu into a div area and refresh it with new results. While I was able to display the data in the div area without the dropdown menu, I am facing difficulty in fetching the required da ...

Verifying credentials using Chromium pop-up window with Playwright

In my current project, I am using Playwright to automate the configuration of multiple devices. However, I have encountered a challenge with certain models that require authentication through a popup dialog box in Chrome. https://i.stack.imgur.com/jgnYM.p ...

Unable to manipulate the marker with the leaflet library

Currently, I am utilizing react.js with the leaflet library and would like to enable marker movement on the map when clicked, instead of adding a new one. Below is the code snippet I am working with: import React from "react"; import { MapConta ...

Navigating Users and Routing with Ionic Framework (AngularJS)

Currently, I am using Ionic for a new project and could use some guidance with routing (I'm relatively new to Angular). These are the states I have defined: $stateProvider.state('map', { url: '/map', views: { map: ...

Is there a way to turn off alerts from Aspx files for HTML and CSS?

Dealing with annoying warnings in my aspx files has been a constant struggle. The "CSS Value is not defined" message pops up when I reference CSS files from different projects, causing unnecessary frustration. Even more frustrating are the warnings about i ...

Exploring the possibilities of accessing Vue.prototype within an .addEventListener function

I've been attempting to access the global object Vue.prototype.$firebase, which is declared in main.js. import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import VueTailwind from "vue- ...

Error in JSON causing issues in UITableView

Having an issue with my app using JSON and a UITableView. Upon trying to build/run the app, I am encountering the error: No known class method for selector 'JSONRequestOperationWithRequest:success:failure Check out my code here: The error is on li ...

Module exists; however, command could not be located

I am experiencing an issue with the rimraf node module. Despite being able to access its folder within the node_modules directory, I am receiving errors indicating that the command for rimraf cannot be found. I have attempted to delete the entire node_mod ...

Generate a selection of complementary, triadic, and monochromatic color palettes using just one hex color code

My goal is to generate three unique color palettes based on a single hex/rgb value given by the user. The first palette will feature the complementary color of the initial input, followed by a full range of colors in subsequent palettes. I aim to expand be ...

Exploring the advanced features of OpenOffice Draw for improved geometry analysis

Struggling with the draw:enhanced-geometry section that involves draw:enhanced-path and draw:equation. I'm working on an OOo converter but can't seem to find any concrete solutions or extensive documentation about this part. Any suggestions on ho ...