When attempting to add a new element to an array, the JSON key is mistakenly assigned a number instead of an array

I'm having trouble creating a JSON object that should look like this:

{
 "sreddy-vm-1":["MyDatabase-1"],
 "sreddy-vm-2":["MyDatabase-2"], 
 "sreddy-vm-3":["MyDatabase-3", "MyDatabase-4", "MyDatabase-5"]
} 

However, the output I'm getting is different.

{"sreddy-vm-1":["MyDatabase-1"],"sreddy-vm-2":["MyDatabase-2"], "sreddy-vm-3":3}

Everything works fine until additional elements are added to the array for sreddy-vm-3, at which point it assigns 2 and then 3. I can't seem to figure out what's causing this issue. As someone new to JavaScript, any help or insight would be greatly appreciated. Thank you!

Code

// snippet of code
$scope.forests = ["MyDatabase-1", "MyDatabase-2", "MyDatabase-3", "MyDatabase-4", "MyDatabase-5"];
$scope.forestsOnHosts = {};
angular.forEach($scope.forests, function(forest, key){
    $scope.forestsOnHosts[host] = function () {
        if ($scope.forestsOnHosts[host] === undefined || $scope.forestsOnHosts[host] === null) {
            console.log('******************');
            return new Array(forest);
        } else {
            console.log(JSON.stringify($scope.forestsOnHosts[host]));
            var arr = new Array($scope.forestsOnHosts[host]);
            return arr.push(forest);
        }
    }.call();
}
console.log(JSON.stringify($scope.forestsOnHosts));

Answer №1

add forest to the array and then return it;

Contrary to what you may think, this code snippet does not result in an array being returned.

Add forest to the array and return it afterward;
return arr;

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

Issues arising when attempting to replicate a fetch object into an undefined object in React.js

I'm facing an issue where I have defined a 'poke' object and when I try to clone an object into it, I only get a promise fulfilled with the object's link , instead of the actual object. Here's the code snippet: let poke = fetch(url ...

Different techniques for using percentages in CSS transformations to create dynamic animations for DOM element translations

I have 14 objects positioned across the dom that I need to animate using the translate property. Currently, I am using transform: translate(x%, y%) for each object, requiring me to calculate the translation amount and apply a CSS style individually. This m ...

Angular JS does not acknowledge null values

Within my controller, the variable $scope.test is assigned a value from the server. When this value is null, line 1 of the code below prints 'null', however it still enters the else condition. I have attempted to use $scope.test != null and $scop ...

The @JsonIgnore annotation in Jax-RS does not seem to be functioning properly after including the service endpoint in the Application

I recently embarked on the journey of developing my first REST API and managed to get it up and running for a brief moment. The core of my API involves an Entity class called User that is linked to another database table named Bookmark. To prevent this ref ...

Posts that are repeated when making an AJAX call in WordPress

I have been experimenting with implementing a 'load more' button feature in my WordPress site. The concept is simple - users click the button, and additional posts are loaded using AJAX without the need for page reload or pagination. Following a ...

"Access denied" message displayed on the MeanJS platform

Is anyone else experiencing a JSON response like this? Objectdata: "User is not authorized"headers: (name) {status: 403statusText: "Forbidden" Scenario: User A successfully posts a product and adds a comment. Result: Success. User B tries to comm ...

Is it possible to search and index nested object keys in JSON using PostgreSQL?

If my database table 'configurations' contains rows with a 'data' column in JSONB format like the example below: { "US": { "1234": { "id": "ABCD" } }, " ...

Challenges with implementing TailwindCSS classes in a Next.js application

I've encountered some issues in my nextJS app with utilizing certain TailwindCSS classes such as top, left, or drop-shadow. Even after attempting to update Tailwind from version 1.9.5 to 3.3.3, I have not seen any changes. I believe that I am import ...

Jolt - Self-contained entity- Iteratively substitute property identifiers

I'm new to working with Jolt. I have a JSON payload that represents logical conditions using AND/OR, and it can include an array of conditions called "conditionPredicates", leading to nested conditions like AND(OR(a, b ,c), OR(d,e)). I'd like to ...

Creating a secure ZIP file with password protection using node.js

Currently, I am faced with the challenge of creating a ZIP file in node.js with password protection. Despite using the "node-zip" module for this task, it lacks the functionality to provide password protection: var zip = new require('node-zip') ...

What is the best way to send form data to MongoDB using React?

I am seeking guidance on how to pass the values of form inputs to my MongoDB database. I am unsure of the process and need assistance. From what I understand, in the post request within my express route where a new Bounty is instantiated, I believe I need ...

The first div should be hidden when the toggle is activated

I am currently working on a CRUD project and incorporating some Javascript/JQuery into it. I have a button labeled "Add", which, when clicked, displays a specific div element. However, I'm facing an issue where the div is already visible before the us ...

Receiving unexpected results when returning a function within a React hook

I'm currently working on developing a custom React hook that will provide users with a function to execute. This hook is designed to generate a function internally. Check out this simplified example // fetch.js import { useEffect, useState} from &qu ...

Choose a particular character in a text that corresponds with a regular expression in Javascript

I am looking to replace the symbols < and > within the text. I have constructed a regular expression as follows: (<span[^>]+class\s*=\s*("|')subValue\2[^>]*>)[^<]*(<\/span>)|(<br(\/*)>) This ...

Playing embedded YouTube videos automatically in Safari 11 without user interaction

I’m encountering an issue with a simple modal dialog: When a user clicks on a button, the modal overlay appears. An embedded YouTube <iframe> is then added. Everything works smoothly in most browsers, except for Safari 11.1. Safari’s new auto ...

A guide to setting up automatic version numbering in package.json using Jenkins

My package.json is structured like this: { "name": "Myproject", "version": "0.4.13", Note: Here 4 is not considered the minor version, instead it's 0013. "dependencies": { "lodash": "^4.0.0", "vinyl-fs": "2.2.1" }, "r ...

Tips for loading JSON data into the select2 plugin

My goal is to extract the last two letters (in this case "VA") from the data attribute (data-code="US-VA") of a jvectormap-element using JVectormap. I want to compare these letters with State objects in the database and then load corresponding counties in ...

Queries with MongoDB RegEx fail to return any matches if the search string contains parentheses

When trying to implement case-insensitivity using regex, it seems to work well for plain strings. However, if special characters like parenthesis are involved in the search query for the name, the database returns no results. For example, a search for "Pu ...

"Unlocking the potential of AngularJS: A guide to accessing multiple controllers

I am trying to set a variable in one instance of a controller and read it in another. The variable I need to set is within the object vm (so $scope cannot be used). This is the code for the controller: app.controller("AppController", function(){ var ...

What are some ways I can effectively implement Tanstack Query's useMutation function?

I am trying to implement useMutation similar to useQuery in my code. However, I encountered an issue where the data is returning as undefined and isError is false. Can anyone help me understand why this is happening and how I can resolve it? `import { us ...