Assigning Dictionary Values to a Variable

I am working with a DropDownList and have a requirement to store values in a javascript variable before setting it on the DropDown. I need to loop through the values and format them as shown below:

var categories = [{
                "value": 1,
                "text": "Keyboard"
            },{
                "value": 2,
                "text": "Mouse"
            },{
                "value": 3,
                "text": "Monitor"
            }];

A sample code snippet that I tried is:

dataType: "json",
data: { categoryId: CategoryHdId },
success: function (data) {
                var categories = [];
                for (i = 0; i < data.length; i++) {
                    case = {
                        "value": data[i].ddlSubCategoryId,
                        "text": data[i].SubCategoryName
                    }
                    categories.append(case);
                }
}

However, this results in a

Syntax Error

and

Uncaught TypeError: categories.append is not a function

I would appreciate any help or suggestions on how to properly set the values inside the loop.

Answer №1

case is a restricted term in JavaScript, thereby it cannot be utilized as a variable name; opt for an alternative. Employ push() to append values to an array.

dataType: "json",
data: { categoryId: CategoryHdId },
success: function (data) {
                var categories = [];
                for (i = 0; i < data.length; i++) {
                   // case = {  reserved word case will throw syntax error  
                      someVar = {      //assign as var if you wish to limit its global scope                 
                        "value": data[i].ddlSubCategoryId,
                        "text": data[i].SubCategoryName
                      }
                    categories.push(someVar);
                }
}

Answer №2

Experiment with the following code snippet

let categoriesList = [];
for (index = 0; index < dataList.length; index++) {
    categoriesList.push({ "val": dataList[index].subCatId, "txt": dataList[index].subCategory })
}

Answer №3

type: "json",
content: { mainCategoryID: MainCategoryId },
onSuccess: function (response) {
                var subCategories = [];
                for (x = 0; x < response.length; x++) {
                    let tempVal = {
                        "val": response[x].ddlSubCategoryId,
                        "label": response[x].SubCategoryName
                    }
                    subCategories.push(tempVal);
                }
}

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

Updating a MongoDB subarray with $set now includes adding a new entry rather than just updating existing ones

When trying to update an object in a sub-array, instead of replacing and updating the data, it adds a new entry. Here is the code from controller.js: const updateSubCategory = asyncHandler(async (req, res) => { const { dataArray } = req.body ...

Looping through JSON keys using ng-repeat in AngularJS

I am currently working on a project where I need to populate some JSON data retrieved from the Google Tag Manager API and then send this information to the frontend which is developed in AngularJS. At the moment, I am utilizing ng-repeat on a card compone ...

Using a for loop, how can the property value be set in another object?

One challenge that I am facing is setting object property values. The object in question looks like this: const newPlan = { name: '', description: '', number: '', monday: { breakfast: '', ...

Issue with managing cursor location using readline in Node.js

Currently, I am developing a console application in Node.js utilizing the readline module to manage cursor positions and obtain user input. Below is a custom library I have created for this purpose: // ReadLine.js const readline = require("readline&qu ...

Accessing children elements using Enzyme

I am looking to create a test where I can check if my shallow enzyme wrapper includes the correct child element. For instance, when I have the given code and my specified wrapper, I want to execute a function like someFn() to retrieve the child elements wi ...

Testing nested mocked functions can be achieved by setting up the necessary mocks

How can I create tests for mocked functions within a mocked function? My goal is to verify that my publish mocked function is called only once. jest.mock('amqplib', () => ({ connect: jest.fn(() => Promise.resolve({ createChannel: jes ...

Unusual actions observed when showcasing PDF files within an HTML environment

Exploring the stack and data: I've been diligently working on integrating a PDF display feature into our AngularJS Kiosk application since yesterday evening. However, I have encountered multiple roadblocks in the process. At present, I have a table ...

A guide on how to pass an object as a parameter when opening a new view in JavaScript using the MVC pattern

Within my application, I have two pages - page A and page B, each with its own model. Both pages are loaded by the HomeController as shown below. public class ModelA { public string UserName { get; set; } public int UserID { get; set; } } public ...

Trouble obtaining dates and values in JSON while analyzing Commodity Data Charts

{ "data": { "success": true, "timeseries": true, "start_date": "2022-02-01", "end_date": "2022-03-02", "base": "RUB", "rates": { ...

troubleshooting problems with AJAX calls and routing in Angular

I am a beginner with Angular and I recently completed a tutorial on Single Page Application development using templates imported from PHP files, along with Resource and Route modules. Below is the JavaScript code from my project: (function(){ var app ...

Is it possible to manipulate the render order in Three.js CSS3DRenderer?

Is there a way to make certain elements appear on top of everything in the scene, regardless of their distance from the camera? I've attempted using zIndex and z-index on the DOM elements that the CSS3DObjects are based on, but it hasn't had any ...

Is AjaxMin's EvalTreatment changing the game for JavaScript minification?

While minifying my project using the AjaxMin.dll with the default settings on every build/deployment, I ran into a problem. One of our third-party JavaScript files contains an eval statement that references variables or parameters which, when minified, cau ...

In search of a TypeScript solution for type guarding

I'm encountering challenges with TypeScript type guarding. My goal is to confirm if path[aPath] is an array containing elements of type Type1, and then add to that array. However, even after using Array.isArray() to check whether the value is an array ...

Error: The database has encountered a duplication error in the followers index of the MERNSM.users collection, with a duplicate key value of undefined

Encountered a MongoServerError: E11000 duplicate key error collection: MERNSM.users index: followers_1 dup key: { followers: undefined }. This is puzzling as there is no unique constraint set in my schema. I am unsure of what could be causing this issue, e ...

What is the reason that modifying a textarea causes the AJAX loading of content to be interrupted?

I am currently developing a feature that allows users to quote comments on my website. When a user wants to reply to a specific comment, they can simply click on the "quote" button next to that comment. This action triggers a script that adds the quoted co ...

Encountered a surprising issue in JSON parsing with React Native - Unexpected character 'U' at

I encountered an error while retrieving data from an API for my application. Despite successfully obtaining the token, an unexpected error still occurred, even after using AsyncStorage.clear() at the beginning of the app. useEffect(() => { AsyncStor ...

Minimize the length of the styled-component class name in the upcoming iteration

Dealing with styled-components in Next along with React can pose a challenge when it comes to ensuring proper rendering of the styled components. To tackle this issue, Next offers the compiler.styledComponents flag within the next.config.js file like so: c ...

Tips for validating an excel file using AngularJS

I am working on developing a file upload feature and I'm in need of validation specifically for Excel files. The structure of my form is as follows: <div class="row"> <input type="hidden" name="key" value="uploads/${filename}"> ...

Mastering the asynchronous nature of Node.js with async/await techniques

Is there a way to synchronize the creation of my customers' shopping cart and the insertion of items using a dynamically generated session id? It seems like the issue lies with the order in which the table (cart) is created. Could someone assist me wi ...

Locate a row in an unselected data table using Jquery based on the value in a td

Is there an efficient way with jQuery to locate a td in a "legacy" datatable that contains my search value, and then navigate up the row tr? I am currently using $('#modalTable tbody').dataTable()[0].rows to retrieve all rows and then iterate th ...