Incorporate variable key-value pairs into a JavaScript array or object

Is it possible to add a key value pair to an existing JavaScript associative array using a variable as the key? I need this for JSON encoding and prefer a simple solution over using plugins or frameworks.

ary.push({name: val});

In the above code snippet, ary represents a new array, name is the variable containing the key, and val holds the value of the entry.

I am implementing this within a loop using jQuery to iterate through form fields.

Answer №1

Using Destructuring in ES6

When working with ES6, one can take advantage of the convenient destructuring assignment feature:

ary.push({[name]: val});

It's worth noting that as this is ES6 syntax, there may be compatibility issues with certain browsers, such as IE and Edge 13. Luckily, Babel can handle transpilation for you.


Supporting Legacy Browsers without ES6

If aiming to support legacy browsers without ES6 support, a different approach is required using square bracket notation:

var obj = {};

obj[name] = val;

ary.push(obj);

For a deeper understanding of the nuances between square bracket and dot notation, check out this informative article.

Answer №2

const arr = [];

function addToArr(key, value) {
   const obj = {};
   obj[key] = value;
   arr.push(obj);
}

addToArr("username", "user123");

After carefully reading your query, all you really need is the following snippet of code

$(your group of input elements).serializeArray();

Good old jQuery at work

Answer №3

In programming, an "associative array" can be thought of as a fancy object. Rather than using the push method, you simply assign properties directly to the object:

items[key] = value;

Answer №4

Below is a helpful code snippet

ary.push( {[name]: val} );

Take a look at the example below

let allData = [{name: "Cat", type: "Animal"}]
let finalData: any = [];
for (let i = 0; i < allData.length; i++)
{
  let obj = allData[i];
  for (let KEY in obj)
  {
    //Adding data to another array as an object
    this.finalData.push({ [KEY] : obj[KEY] });
  }
}

Answer №5

let newStyles = [];
for (const s of styles) {
  const tempStyle = {};
  tempStyle[`${style}`] = `../dist/css/custom.${file}.${style}.css`;
  newStyles.push(tempStyle);
}

data : {"blue-yellow":"../dist/css/custom.theme.blue-yellow.css"}

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

Error: Attempting to access the value property of a null object within a React Form is not possible

I am currently developing a form that includes an HTML input field allowing only numbers or letters to be entered. The abbreviated version of my state interface is outlined below: interface State { location: string; startDate: Date; } To initiali ...

Retrieve the processed data from a file using node.js

I have successfully read and parsed my file, however I am facing an issue with retrieving the output string. I want to access this string from a variable assigned to it on the client side. Despite using async series to handle callback functions effective ...

Is there a way for me to retrieve SCSS color variables within the javascript of a Vue template?

I have a unique challenge in my application involving a component called Notification. To bring notifications to other components, I utilize the mixin method toast('message to display', 'color-variable'). My goal is to set the backgroun ...

What steps can I take to stop Google Maps from resetting after a geocode search?

As a beginner working with the Google Maps Javascript API v.3, I have written some code to initialize a map, perform an address lookup using the geocoder, re-center the map based on the obtained lat long coordinates, and place a marker. However, I am facin ...

Executing a jQuery AJAX function when the timeout occurs

My goal is to dynamically reload my jQuery DataTables without having to refresh the entire page in order to fetch new data. Here's the initial function I have set up to kick off the process: $(document).ready(function() { $.ajax({ url:&apo ...

Utilizing reflection in Unity to dynamically convert a List into JSON format

I'm facing a complex situation and seeking advice to resolve it. Previously, I posted a question on Unity's saving functionalities which can be found here: Unity save everything (snapshot) Currently, I am attempting to serialize everything into ...

When HTML/JS code is utilized, the submit button or image should function to open the same page as

In addition to the left and right mouse buttons, you also have a middle mouse button. If you click on an image or hyperlink with this middle mouse button while browsing any website, it will open a new window in the background. Now, I want to achieve a sim ...

Updating nested JSON object with key/value pair in MySQL 5.7

I have been experimenting with the new API for mysql 5.7 that is designed for handling JSON columns. The test column in my database looks like this: {"foo":{"efg":1}, "bar":{"abc":0}} My goal is to append a new key-value pair to one of the keys, for exam ...

Can the line "as is" be included in HTML code?

Can I incorporate the following JavaScript and JSON expressions directly into HTML code? CONTRATE > 50 && SALINC <= 50 || RETAGE >= 50 { "CONTRATE": 0, "SALINC": 0, "MARSTATUS": "single", "SPOUSEDOB": "1970-01-01" } I want to be able to ...

Set the Vue 3 Select-Option to automatically select the first option as the default choice

I am attempting to set the first select option as the default, so it shows up immediately when the page loads. I initially thought I could use something simple like index === 0 with v-bind:selected since it is a boolean attribute to select the first option ...

Discovering parent elements far up the DOM hierarchy using jQuery

I'm a bit confused about how to locate an element that is a parent element further up the tree. $('.btn-action').hover( function(){ $(this).find('.product-card').addClass('animated bounce'); }, function(){ ...

Parsing improperly formatted JSON from an HTTP GET request can be done using either AngularJS or JQuery

Trying to decipher a poorly formatted JSON response from a remote server that looks something like this: //[ {},{} ] In my AngularJS code: $http.get('http://www.example.com/badjson') .success(function(data) { console.log(data); }) ...

Modify the JSON structure of a deeply nested object

I am attempting to convert a deeply nested JSON object from one structure to another so that it can be properly used with the jQuery Nestable library. Here is the original format I am working with: { "scanned": { "a3": { ...

Inability to assign a value to an @input within an Angular project

I recently started using Angular and I'm currently trying to declare an input. Specifically, I need the input to be a number rather than a string in an object within an array. However, I'm encountering difficulties and I can't figure out wha ...

Issue with Three.js Raycaster failing to intersect with a custom vertex shader

I'm currently working on implementing a particle system using a dedicated Vertex shader. I have provided a code example for reference: https://jsfiddle.net/dthevenin/7arntcog/ My approach involves utilizing a Raycaster for mouse picking to enable int ...

What are some strategies for extracting additional information from a JSON file that spans multiple pages?

I am trying to figure out how to display a list of all characters when using a search bar. Currently, I can filter characters but the JSON data has multiple pages which limits the number of characters displayed. I have implemented logic to move to the next ...

Ways to implement standard sorting in react-table

Currently, I am utilizing react-table v7 to generate tables. You can find more information about react-table at https://www.npmjs.com/package/react-table. While working with the table, I was able to implement sorting for all columns by following this e ...

Creating a customized greeting message using discord.js

I've been working on creating a Discord bot using discord.js, and I'm trying to figure out how to make the bot send a welcome message when a new member joins the server and opens a chat with the bot. The message should be something like "Hi there ...

Is it possible to use header() function in a file that is being accessed through

In a specific package, there is a crucial file that verifies session data and redirects the user to the login page with an error message if no valid session exists, using header("Location:" . $var);. This particular file is included in almost all files wi ...

Listening to multiple events in AngularJS using `$scope.$on`

I am faced with a situation where I need to respond to two different events being transmitted via $scope.$emit and take action only when both have occurred. For example, if the events are triggered in the following sequence: $scope.$emit('first&apos ...