Generating JSON array objects dynamically in JavaScript code

Need help with organizing my code

let newArr = [];
$.post( "/reports/search", { query:'*'},function(data) {
    for(let i=0; i<data.length; i++) {
        newArr[i].value = data[i].name;
        newArr[i].data = data[i].id;
    }
},'json');

I am trying to create a JSON array variable with a specific structure

newArr = [ {"value":"aaa", data:"1"},
           {"value":"bbb", data:"2"},
           {"value":"ccc", data:"3"}
]

Any suggestions on how to achieve this in JavaScript?

Answer №1

This code snippet is fully compatible with all up-to-date web browsers:

let array = data.map(function(item){return {val: item.title, info: item.code});

If utilizing ES6 features such as deconstruction and aliasing:

let array = data.map(({title: val, code: info}) => ({ val, info }))

Answer №2

It is important to create the object first before assigning values to its properties:

var arr=[];
$.post( "/reports/search", { query:'*'},function(data) {
    for(var i=0;i<data.length;i++)
        {
            arr[i] = {};
            arr[i].value=data[i].name;
            arr[i].data=data[i].id;
        }

},'json');

Alternatively, you can achieve the same result in one step using an object literal:

var arr=[];
$.post( "/reports/search", { query:'*'},function(data) {
    for(var i=0;i<data.length;i++)
        {
            arr[i] = {
                value: data[i].name,
                data: data[i].id
            };
        }

},'json');

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

Displaying a pop-up window upon clicking on an item in the list view

After creating a list where clicking an item triggers a popup, issues arose when testing on small mobile screens. Many users found themselves accidentally tapping buttons in the popup while trying to view it. What is the most effective way to temporarily ...

Having trouble retrieving values from my EXPRESS / NodeJs response error message: [String: 'Error: Request resulted in an error code: 404'

I have been attempting to retrieve values from my express response error. When I use console.log on the error like so... app.use(function(err, req, res, next){ console.log(err) }); The content displayed in the console is as follows: [String: 'E ...

Tips on how to correctly pass a .JSON object in the setState function of a reactJS

I am having an issue when attempting to pass a .json file in the following format: this is my class import MyForm from './MyForm'; class CreateProject extends React.Component{ constructor(){ super(); this.state = { categori ...

Unlocking the Power of Localization: An Easy Guide to Accessing JavaScript Values

After utilizing the localization helper created by Matt Hawley, I found it to be incredibly effective. However, I am encountering an issue when attempting to retrieve the values in javascript/jQuery. For example, I am unable to fetch the resource text usi ...

The error message "reload is not defined" indicates that the function reload

Initially, I encountered the error TypeError: require(...) is not a function, prompting me to add a semicolon at the end of require("./handlers/slashcommands"). However, this led to a new issue: ReferenceError: reload is not defined. This occurre ...

Ways to assign a default value to a radio button using a mock JSON dataset

As a beginner in AngularJS2, I am looking to resolve an issue where the checkbox is automatically checked when retrieving values from a mock JSON file. Can someone please help me? <div class="form-row"> <div class="formHeading">Skills *< ...

VueJS: Unable to access the 'name' property as it is undefined"

I'm at a loss trying to figure out a solution for this issue. My current task involves editing a pub schedule using an edit form: pubs/UpdateProfile.vue <template> <confirm title="Edit Pub" ok="Save pub" :show="show" v-on:save="sa ...

"Utilizing Jquery for interactive menu functionality - delivering the requested JSON

I have successfully implemented a dynamic menu using jQuery that parses a JSON response file to create the menu. However, instead of having the menu items link to URLs, I want them to retrieve and parse JSON data from those URLs. Despite my efforts, the me ...

Issue 500 encountered while implementing VB.NET with jQuery AJAX

Having trouble populating a select option using jQuery ajax, and I could really use some assistance! Encountering the following error: Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://localhost:20440/admin ...

What is preventing the control from being passed back from the PHP file to the AJAX success function?

My website is built using PHP, Javascript, and AJAX. Below is the essential code snippet: JS code (AJAX function): $("#btn_add_event").click(function(){ var strSeriaze = $( "#formAddEvent" ).serialize(); url = $( "#formAddEvent" ).attr('act ...

Node server encountering issue with undefined data in POST request

I have been working on an Angular2/Node.js application. Everything seems to be working fine when I retrieve an object from the Node server, but I'm facing an issue when trying to post data to the server. The request.body always shows as undefined. Can ...

Ways to efficiently update styles dynamically using css and/or javascript

I am trying to update the styles of a button when it is clicked. I initially set the style for the first element on page load, but now I need to remove those styles from the first element and apply them to the clicked button instead. I am having trouble fi ...

In ReactJS, ensure only a single div is active at any given moment

I'm working on a layout with three divs in each row, and there are multiple rows. Only one div can be selected at a time within a row, and selecting a new div will automatically unselect the previously selected one. Here is a simplified version of my ...

Delete the hidden attribute from an HTML element using a JavaScript function

Hey there! I have a question for you. Can you assist me in removing an attribute (Hidden) using an Input type button? Here is the script: Thank you for your help! <input type="button" onclick="myfunction()" value="Test"> <hr> <button id= ...

Modify session variable upon link click

Here is an extension of the question posed on Stack Overflow regarding creating a new page for different PHP ORDER BY statements: Create a new page for different php ORDER BY statement? The task at hand requires changing a session variable and refreshing ...

Retrieve client-side environment variables

When making multiple API calls within my components using the fetch method, I found myself constantly having to determine which environment I was in. To streamline this logic, I created a Utils class that provides the appropriate base URL: export default c ...

Scraping a URL that functions perfectly on Firefox without the need for cookies or javascript results in a

Despite blocking all cookies and turning off JavaScript on Firefox, I encounter an issue when attempting to scrape a URL using Python's urllib module. The error message HTTP Error 403: Forbidden is returned. I have ensured that I am using the same use ...

Exploring Angular's Dependency Injection

How can I verify that a module has properly loaded its required dependencies? I've added ngAnimate to the module definition, but it doesn't appear to be functioning within the application when it runs. The environment I'm navigating is quite ...

Unable to set an onclick function within a customized dojo widget

I have a custom widget that I've defined as shown below: dojo.declare('myWidget', [dijit._WidgetBase, dijit._Templated], { 'templateString':'<span>' + '<a dojoAttachPoint="linkNode" href="b ...

Enhance the HTML content using a JavaScript function

Here is the code that I have: <label>Brand</label></br> <select name="brand" id="brand" onChange="changecat(this.value);"> <option value="" selected>Select Brand</option> <option value="A">AMD</option&g ...