Adding an item to a JSON array with a variable as the key in a multi-dimensional structure

A JSON file contains an array like this:

{
    "general_array":[
        {"key_1":["a","b","c"]}
    ]
}

My goal is to add a new element to the array, for example:

{"key_2":["d","e","f"]}

The value of the new key comes from a variable:

var newKey = 'key_2';

I attempted to add the element to the existing array using this code snippet:

// ... obtaining file content
// var jsonFileContent = '{"general_array":[{"key_1":["a","b","c"]}]}';

var jsonObj = JSON.parse(jsonFileContent);

var newKey = 'key_2';

jsonObj.general_array.push({newKey:['d','e','f']});

var newJsonFileContent = JSON.stringify(jsonObj);

// rewriting the file ...
// console.log(newJsonFileContent);

However, the resulting file shows:

{
    "general_array":[
        {"key_1":["a","b","c"]},
        {"newKey":["d","e","f"]}
    ]
}

Instead of the value of the variable, the name of the variable is added as a new element key.

How can I add the actual value?


UPDATED

The method using [newKey] functions in most browsers but not in Internet Explorer 11.

I require a solution that works across all browsers, including IE11. This query remains unresolved.

Answer №1

If you want to retrieve the value of a variable as a key name, you can utilize [newKey]:

var dataContent = `
{
    "numbers_array":[
        {"num_1":["1","2","3"]}
    ]
}`;
var dataObject = JSON.parse(dataContent);

var newKeyType = 'num_2';

var tempDataObj = {};
tempDataObj[newKeyType] = ['4','5','6'];
dataObject.numbers_array.push(tempDataObj);

var updatedDataContent = JSON.stringify(dataObject);
console.log(updatedDataContent);

Answer №2

If you want to use the value of a variable as a JSON key, simply enclose it in square brackets like this:

{[dynamicKey]:['x','y','z']}
let jsonData = '{"main_array":[{"key_1":["m","n","o"]}]}';
let jsonObject = JSON.parse(jsonData);
let dynamicKey = 'another_key';
jsonObject.main_array.push({[dynamicKey]:['x','y','z']});
let newJsonData = JSON.stringify(jsonObject);
console.log(newJsonData)

This is called the computed property name syntax, which provides a more concise way of assigning values to object properties.

Answer №3

Consider updating the following line:

jsonObj.general_array.push({newKey:['d','e','f']});

Replace it with this:

var newObj = {};
newObj[newKey] = ['d','e','f'];
jsonObj.general_array.push(newObj);

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

Utilize JavaScript to parse a JSON object

Hey there, I'm having an issue with reading a JSON object using JavaScript. Here's the snippet of code that I'm currently working with: $.ajax({ url:'index.php/usuarios/getUsuarioById', type: 'POST&a ...

Solving the puzzle of filtering nested arrays in JavaScript

Consider a JavaScript object representing JSON data like this: [ { "Id": "8868dfdd-9b4e-4bad-a4ce-ecae6a3cc828", "Name": "Company 1", "Locations": [ { "Id": "bd017b9c-b62e-43aa-9f00-c164a855eed1", ...

Tips for integrating execute_script and WebDriverWait in Selenium automation

Is there a way to combine execute_script() and WebdriverWait? In my current code: network_list = driver.find_element_by_xpath('//*[@id="folder_box"]/div[1]/div/div[2]/div[1]') wait = WebDriverWait(driver, 4) try: wait_network_list = wait.unt ...

Error in Angular google maps click event: Property 'click' is not readable because it is undefined

Currently, I am utilizing angular google maps in conjunction with the ionic framework to obtain coordinates when a user clicks on the map. Below is an example of how the directive is injected into the view: <ui-gmap-google-map center="map.center" zoom= ...

Unable to modify data values within the MongoDB database

After executing this code, the username is not updated. I attempted using UpdateOne as well but that didn't solve the issue either. The initial intention was to update an array, but changing the username was a troubleshooting step. const mongoose = re ...

Issue: The key length and initialization vector length are incorrect when using the AES-256-CBC encryption algorithm

Within my coding project, I have developed two essential functions that utilize the AES-256-CBC encryption and decryption algorithm: import * as crypto from "crypto"; export const encrypt = (text: string, key: string, iv: string) => { con ...

Converting JodaTime LocalTime to JSON - Real-life Stack Overflow Experience

My current task involves serializing Java objects to JSON. Within my Java objects, there is a field that contains a JodaTime LocalTime object. Many of these Java objects also contain fields that are Collections which could potentially be empty. To avoid h ...

Creating a User and Friend system using Firebase integration with AngularFire

I am currently working on incorporating AngularFire into my Google Firebase Ionic app, and I am encountering difficulties with the database structure and its implementation. My objective is to have users in the database along with basic information such a ...

Iterating through a nested JSON object using Java

I am currently working with a JSON object that contains nested child objects. My goal is to loop through the entire structure and extract all account_id's and id's when they appear together in the same child object, storing them in a single array ...

What is the process for transforming a key-value object from JavaScript to TypeScript?

I am currently facing a challenge in converting a JavaScript object into a TypeScript version as part of our code refactoring process :( I am struggling to figure out how to properly migrate a JS JSON object into a correct TS format. For instance, consider ...

What is the process for deleting headers in a $http.get call and simultaneously including "application/json" and "text/plain" under the "Accept" header?

I'm relatively new to angularjs and I'm currently working on implementing some new features to an existing Angular JS application. The current API calls are quite intricate so I decided to make a direct call. Below is the code snippet for my new ...

Guide on showcasing the selected items from a multiselect dropdown in an Angular 8 table cell

I have a form with dropdowns and multi-select dropdowns. Upon submitting the form, the values are displayed in a table. For the multi-select option, users can choose multiple values, which are then saved as an array like this: [ {id: "xyz", name: "Develop ...

The challenge of implementing dynamic table rows in Vue.js

While using Vue.js to dynamically create table rows, I encountered an issue where the price in the previous row's textbox gets cleared when adding a new row. The problem seems to be related to setting the price value only when selecting a product, but ...

When the <div> element appears, it should cause the images below to be pushed downward

I have an HTML file where clicking on an image opens a box with text below it using jQuery. Is there a way to push the images under the box down to ensure that the box never covers an image? It needs to be responsive as well. Here is the fiddle link: Bel ...

Click on a React component to receive its property

Hey there! I'm currently in the process of developing an app that allows users to search for books and organize them onto specific shelves with just a click. Right now, users can type a query and see multiple results displayed on the screen. My goal i ...

Freeze your browser with an Ajax request to a specific URL

There is a function in my view that transfers a value from a text box to a table on the page. This function updates the URL and calls another function called update_verified_phone(). The update_verified_phone() function uses a model called user_info_model( ...

Displaying outcomes solely based on JSON upon choosing a filter

Goal I aim to only show results once their respective state is chosen. Currently, all results are displayed automatically upon page load. I prefer if nothing is shown initially. Only when a state is selected should the corresponding results appear. Bac ...

Why won't the div move when I click it?

Could you please explain why my JavaScript code isn't functioning as expected? The intended behavior is for the 'mark' div to move to the current mouse coordinates upon clicking within the map. ...

Trouble with scrolling child panel to top of screen in Angular 8

I am facing an issue with a parent component that contains four child components. Each child component is a primeNg panel with a form embedded in it. While the first three panels are always expanded, the fourth one is collapsed initially. Inside this fourt ...

Developing New Arrays from JSON Responses using AngularJS

I have a function linked to the factory for controlling: fac.GetDailyCountersList = function () { return $http.get('/Data/GetDailyCountersList') } Within the controller, this is how the function is invoked: $scope.DailyCounters = null; Dai ...