Combine several dictionary values under a single dictionary key in JavaScript

I have a unique dictionary structure displayed below. My goal is to populate it with values in a specific way. It all begins here

var animals = {
        flying : {},
        underground : {},
        aquatic : {},
        desert : {}
    };

To illustrate this process: Let's say I want to insert

d = {dove : [<some list>] }
into animal[flying], how would that be accomplished? Since manually entering the values isn't an option and I'm using a loop, I can enter them manually but not programmatically.

I attempted animals[flying] = d, which worked initially, but when trying to add another value, it replaces rather than appends.

In the end, my desired outcome is something like this: This is what we aim for

var animals = {
        flying : {
            dove : [<list>],
            sparrow : [<list>],

        },
        underground : {
            rabbits : [<list>],
            squirrel : [Squirrel],

        },
        aquatic : {
            dolphin : [<list>],
            whale : [Squirrel],

        },
        desert : {
            camel : [<list>],
            antelope : [<list>],

        },
    };

Answer №1

Because...

myDict[subcat] = x 

This code assigns a value to a key in a dictionary. However, if you want to append the variable to an array instead of overwriting it, you need to use the push method (keep in mind this is not Python - arrays are called Arrays and dictionaries are Objects). To achieve this, initialize an empty array for each key in the dictionary as shown below:

myDict = {
    subCat: [],
}

Then, during the loop, push the variable into the array like this:

myDict[subCat].push(x)

Answer №2

One possible solution could be:

animalTypes["flying"] = Object.assign(animalTypes["flying"], data);

For example:

animalTypes = {
    flying: {}
}

data = { eagle: [3, 4, 5] }
Object.assign(animalTypes["flying"], data);
data = { hawk: [6, 7, 8] }
Object.assign(animalTypes["flying"], data);
console.log(animalTypes); //{"flying":{"eagle":[3,4,5],"hawk":[6,7,8]}}

Answer №3

let newestAnimal = {species: 'parrot'};    
if(birds['flying']['parakeet'] && birds['flying']['parakeet'].length > 0) {
   //List already exists so insert the newest animal
   //TODO also verify if the animal is already in the list?
   birds['flying']['parakeet'].push(newestAnimal);
}else {
   //Create a fresh list
   birds['flying']['parakeet'] = [newestAnimal];
}

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

Whenever a click event is triggered, the Vue method is executed twice

Why is the set method being executed twice? Check the console when you click the star. Removing @click="set(rating)" results in no action, indicating it is not called elsewhere. http://jsfiddle.net/q22tqoLu/ HTML <div id="star-app" v-cloak> ...

Using jQuery to iterate through elements of a PHP array

I've got a PHP array that outputs like this: Array ( [0] => Array ( [title] => Much title [end] => Such end [start] => Very start ) [1] => Array ( [title] ...

Using a CSS button to activate a JavaScript function: A step-by-step guide

My current project involves writing a script to change the color of text when a specific button is clicked. The idea is that clicking the "Change color1" button triggers the text color change using the following code snippet: <button onclick="myFunction ...

Looking for a way to extract Regular Expressions from an IgGrid cell in Infragistics?

Is it possible to apply a regular expression to a igTextEditor within an igGrid Updating? I attempted to utilize the validate option, but it was unsuccessful. $("#schedulerTable").igGrid({ columns: $scope.schedulerColumns, widt ...

Transferring large amounts of data to Parse.com in bulk

I am facing a challenge with importing approximately 10GB of data into Parse. The data is currently in JSON format, which makes it suitable for using the Parse importer tool. The issue I am encountering is that these objects do not have unique identifiers ...

Best method for retrieving JSON information from the internet using an API

Looking to work with a URL like this: http://site.com/source.json?s= My goal is to develop a Python class that can take in the "s" query, send it to the specified site, and then extract the JSON results. I've made attempts at importing json and set ...

Animations do not trigger with content changes in AngularJS ngIf

According to the Angular documentation on ngIf, animations occur just after the contents change and a new DOM element is created and injected into the ngIf container. Animations In my experience, I have encountered issues with this behavior. To demonstra ...

Combining Javascript and Django for a powerful web development solution

Having trouble setting up JS on my Django web app, despite reading through the documentation and previous queries. Using the Django dev server with the following file structure: mysite/ __init__.py MySiteDB manage.py settings.py ...

AngularJS is capable of executing conditional logic using the if/else statement

I am attempting to set the inputLanguage value to 'en' and encountering an error that says english is not defined. Here is the code snippet from my alchemy.js file: module.exports = function(Alchemy) { Alchemy.language = function(inText, inp ...

Guide to developing a reusable component or partial in react.js

My first experience with React.js involved a relatively simple task. I started by creating an app.js file that loads the initial page, containing my navigation menu and rendering the children props. However, I realized that instead of keeping the navigat ...

Create JSON: Eliminate any empty fields

When working with a Ruby-on-Rails API, I am facing an issue with null fields in the rendered JSON: def index @items = Item.all render json: @items, end If my Item objects have nil fields, they show up as null in the JSON. I want to remove these null ...

Resource loading error: The server returned a 404 (Not Found) status code, as shown in the console

Click here I have a simple file structure where index.html, script.js, and login.js are all in the same root folder without any subfolders. The issue I'm facing is that although the connection to the database works fine, there seems to be a problem wi ...

Where can I locate htmlWebpackPlugin.options.title in a Vue CLI 3 project or how can I configure it?

After creating my webpage using vue cli 3, I decided to add a title. Upon examining the public/index.html file, I discovered the code snippet <title><%= htmlWebpackPlugin.options.title %></title>. Can you guide me on how to change and cu ...

Tips on displaying hyperlinks within a text area in an Angular application

In my Angular application, I am facing an issue with displaying hyperlinks within a text area box for dynamic content. The hyperlinks are not recognized and therefore cannot be clicked. Can someone please advise on how to properly display hyperlinks with ...

The correct reading of JavaScript in HTML is a common source of confusion

After creating a basic application using the code provided in a forum thread and testing it on the worker sandbox MTurk site, I noticed a peculiar issue. The application runs smoothly when following the code from the forum answer directly. However, when at ...

Example JSON response for RabbitMQ API management module

Currently, I am in the process of gathering all the data offered by the RabbitMQ Management API. I have successfully set up my own RabbitMQ environment locally and have been able to retrieve the API responses. However, I am unsure if I have accessed all ...

Using Java classes for the deserialization of Json in Android applications

Using asp.net web api on the server and android on the client, I am making a request from android to the web api and receiving a JSON string. However, when I try to assign this JSON string to a Java object using Gson, an exception is thrown. Here is my cod ...

How to prevent uncaught errors when checking for undefined in if statements and dealing with undefined items

It appears that there are not many oboe tags being used on SO, but any assistance with this general JavaScript question regarding handling uncaught errors for undefined would be greatly appreciated!~ I am currently utilizing Oboe.js to stream data to a we ...

I am interested in displaying the PDF ajax response within a unique modal window

With the use of ajax, I am able to retrieve PDF base64 data as a response. In this particular scenario, instead of displaying the PDF in a new window, is it possible to display it within a modal popup? Any suggestions on how this can be achieved? $.ajax ...

What is the process of dynamically loading CSS into an HTML document?

In my C# program, I am utilizing a web browser control and setting its HTML property programmatically by loading it from an HTML string variable. While this setup works almost perfectly, I have noticed that it loses the reference to the CSS file. I believe ...