JavaScript: Generate a JSON object with customizable key-value pairs

Suppose we have two arrays containing possible numerical values:

var reg = [1000, 1010, 2050];
var ag = [100, 101, 102];

The objective is to create an object/json structure like this:

{ 1000 : [100, 101], 1010 : [100, 101, 102], 2050 : [100, 102]};

These values will be obtained from checkboxes that the user selects:

<input type="checkbox" data-reg="1000" data-ag="100" class="agcheck" />
<input type="checkbox" data-reg="1000" data-ag="101" class="agcheck" />
...
<input type="checkbox" data-reg="xxx" data-ag="yyy" class="agcheck" />

The 'xxx' and 'yyy' represent all possible values from the arrays.

var obj = {}; //or var arr = [];
$('.agcheck:checked').each(function(){
    var ag = parseInt($(this).data('ag'));
    var reg = parseInt($(this).data('reg'));
    // What needs to be done here
 }

How can we achieve this object structure in JavaScript?

Within the loop:

  • We cannot use obj.reg.push(ag) because it would result in "Cannot read property 'push' of undefined"
  • We cannot use obj.push(reg:ag) as it would lead to an array like [0:[reg:100], 1:[reg:101]...] with the key not being set correctly
  • We don't want obj.push({'reg':reg,'ag':ag}) either, because we want the reg value to act as the key.

====

With the help of #SLaks's answer, I was able to solve this issue:

var obj = {}; //or var arr = [];
$('.agcheck:checked').each(function(){
    var ag = parseInt($(this).data('ag'));
    var reg = parseInt($(this).data('reg'));
    if (obj[reg] == undefined) {
        obj[reg] = [];
    }
    obj[reg].push(ag);
 }

Answer №1

If you want to assign a value to a property of an object, you can do so using bracket notation:

obj[name] = value;

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

What steps should be taken to set up the datatable to sort records in descending order based on the creation date?

In my Rails application, I am utilizing the Datatable plugin to display data on the User index page. The first column in the index page is the created_at field, which displays dates like Mon, 17-Oct-16. I want to sort this column in descending order base ...

Using Ajax with Laravel for Beginners

After clicking a button in my Laravel app, I want to update some data in the database using ajax without reloading the page. This is a simple ajax request where only a function in a controller needs to be invoked. I tried setting up the ajax request follo ...

Stripping double quotes from json output

Using a basic array to reference icons like so: {name: "text", avatar: srcs[15]} has been working perfectly. However, I am now dynamically creating an array from my JSON API, resulting in an array of objects structured like this: {name: "text", avatar: ...

Failure to process JsonWebTokenError due to a corrupted signature in the middleware

I am facing an issue with my middleware when the jwt.verify(request.token, process.env.SECRET) function raises a JsonWebTokenError: invalid signature with middleware error upon receiving an invalid token. Despite configuring my middleware correctly, this e ...

What is the best way to retrieve "Results" data from a JSON file in order to perform calculations using NumPy?

Just beginning my Python journey with Boto3, working on parsing a JSON file: Student = [{"Student_ID": 1, "Name":"Erik", "ExamSubject": "English", "Result": "72.3", "ExamDate": "9/12/2020", "Gender": "M"}, {"Student_ID": 2, ...

Toggle Jquery menu with a click of a button

I need help with creating a menu for a forum that opens on click and closes on click. Here is the code I have so far: /*Custom BBPress admin links menu*/ function wpmudev_bbp_admin_links_in_menu($retval, $r, $args) { if ( is_user_logged_in() ) { $me ...

A step-by-step guide on converting the contents of a PHP nested array into JSON objects nested within an outer array by utilizing

Here is an array I am working with: $myAssocArray = array( ['fred','tyson',23], ['collins', 'white', 54], ['mary', 'frost', 46] ); After using json_encod ...

Tips for restricting the size of inserted content in a contentEditable paragraph

I am in need of a one-line editable paragraph that can contain text without overflowing its size. Currently, I am using CSS to hide the overflow and prevent multiple lines by not displaying the children of the paragraph. However, what I really want is fo ...

There is a delay in updating ng-if/ng-hide in real time on the HTML page

Assistance needed for implementing a slight adjustment in AngularJS with TypeScript. The requirement is to change the text of a button for 3 seconds upon clicking, then revert back to its original text. Two HTML elements are created for this purpose, each ...

Fetching post data from an HTML form in Node.js using Express 4: A comprehensive guide

This is the content of my main.js file: var express = require("express"); var app = express(); var bodyParser = require("body-parser"); var userAPI = express.Router(); app.use(express.static(__dirname + '/public')); app.use( bodyParser.json() ) ...

Exploring the power of Knockout Js and Typeahead libraries

https://i.stack.imgur.com/38iZc.png Hello experts in Knockout and typeahead, I am receiving suggestions from the typeahead js as shown above. I have my data supplied in an array format var itemsRandom= ['Apple', 'Ball','Ape&apos ...

Passing the app variable from Express.js to routes

I am attempting to transfer some data from the app (variable defined as var app = express();) to some Socket.IO related code by sending a value to a middleware in a similar manner: function routes(app) { app.post('/evento', function (req, re ...

What is the best way to insert a button at the end of the last row in the first column and also at the

I am working on a JavaScript project that involves creating a table. My goal is to dynamically add buttons after the last row of the first column and also at the top of the last column. for (var i = 0; i < responseData.length; i++) { fo ...

Exploring the object tag box model and its properties for width and padding in Firefox version 6

Hey there, I've been puzzled by the fact that my Firefox browser seems to be using a different box model for my video embeds compared to Chrome. Even though the same CSS rules are being applied, if the object tag includes attributes like data="whateve ...

Is Three.js deprecating the setHSL() function?

Searching for a solution to incorporate an HSL color scheme into my threejs project. The documentation seems to lack information on using .setHSL() or .offsetHSL() post-2013. Is there a preferred method to exclusively utilize HSL in a threejs scene? Appre ...

Issue with line breaks when using json_encode and json_decode with textareas

I encountered an issue with line breaks in a textarea field. Here is the form structure that includes the textarea: <form method="post" action="index.php"> <label><textarea name="content_stream"></textarea> </form> When inse ...

C++ Ping Pong Board Using a 2-Dimensional Array

I'm struggling to debug my code where I am attempting to create a "board" and draw an image on it using X and Y coordinates. The issue is that the character I want to draw keeps appearing multiple times. Here is the snippet of my code: class Board { ...

NodeJS Fork - React each instance a new line is detected from the child process

I am currently working on creating a NodeJS function (on Windows7) that listens to a subprocess and handles each newline sent through the subprocess in Node. The following example demonstrates this: var express = require('express'); var app = ex ...

Reading a json array containing multiple arrays from PHP to Java

I'm facing an issue with parsing a JSON response generated by PHP and sent to my phone as JSON via HTTP. The response contains an array with 3 nested arrays like so: $arr = array(); To populate this array, I query my MySQL database for specific IDs ...

Tips for utilizing window.scrollTo in order to scroll inside an element:

I'm experiencing an issue where I have a vertical scrollbar for the entire page, and within that, there's an element (let's call it 'content') with a max-height and overflow-y scroll. The 'content' element contains child ...