Include a new element in the JSON object

Is there a more elegant way to add a field to JSON without using eval? My current solution works but is not very clean.

var json = {};
var id = "test";
eval("json." + id + " = 5;");
console.log(json.test);

UPDATE: Apologies for any confusion in my question. I am looking for a method that utilizes the value of the variable id for the new field.

Cheers, Bernhard

Answer №1

Here is an alternative method:

Instead of using the previous syntax, try this:

json[id] = 10; 

So, in your scenario:

var jsonNew = {};
var idNew = "example";
jsonNew[idNew] = 10;
console.log(jsonExample); //prints 10
// OR
console.log(jsonNew['example']); //prints 10

Answer №2

Here is a simple way to add properties to a JSON object:

var myObj = {};
myObj.name = "John";
console.log(myObj.name);

Alternatively, you can also do it like this:

var myObj = {};
myObj["name"] = "John";
console.log(myObj.name);

I hope this explanation proves helpful!

Answer №3

You have a few options for creating and accessing objects in JavaScript.

var data = {};
var key = "example";
eval("data." + key + " = 10;");
console.log(data.example);

Another method is to directly assign the property value:

var data2 = {};
data2.example = 10;
console.log(data2.example);

Alternatively, you can use square bracket notation:

var data3 = {};
data3["example"] = 10;
console.log(data3.example);

The first method shown should be avoided due to potential drawbacks.

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

Creating Interactive Image Thumbnails with jQuery Dialog in ASP.NET MVC 4

Trying to implement a small functionality using jQuery and ASP.NET MVC 4, I encountered a problem. The issue lies with a list of thumbnails that represent products in my application: <ul class="thumbnails"> @foreach (var thumbnail i ...

Is caching a feature in AngularJS, and are there methods available for disabling it?

var modalInstance = $modal.open({ templateUrl: '/template/edit-modal.html', controller: ModalInstanceCtrl2, resolve: { locations: function () { return locationToEdit; } }, scope: $scope.$new() }); ...

Retrieving JSON Data from Django Server

UPDATE: I am currently working on a project that involves the following steps: Submit a POST request with a file in the template --> Process the file in the view to generate an ID --> Display the ID in the template I am relatively new to Django and ...

Using JSON to populate a ListView in an Android application

Currently, I am struggling with understanding the concepts of ListView and list adapters. Any guidance on what might be incorrect in my code and how to rectify the issue would be greatly appreciated. As a beginner attempting to work with ListView, I acknow ...

How can I center a Bootstrap modal vertically and make it responsive?

Is there a way to vertically center the bootstrap modal? I have been searching for a solution, but none seem to be responsive or effective. My website is using Bootstrap 3. The modal does not adjust properly on smaller screens or when the browser window i ...

Unable to send a Json Array in the body of a Restassured request - encountering java.lang.IllegalStateException: The content is not a valid JSON Object

I'm attempting to send a list of objects as the body in a restassured request: Transaction transaction1 = new Transaction(); Transaction transaction2 = new Transaction(); List<Transaction> transactionList = new ArrayList<Transaction>(); t ...

How to Trigger an ascx.cs Function from an ascx Page with JavaScript

I'm currently working with a code behind file that includes a method: public string ProductsAsJson() This method is responsible for returning a JSON representation of multiple products. In order to integrate some Angular functions into my ascx page, ...

My code seems to be malfunctioning

I'm attempting to conceal the chatname div. Once hidden, I want to position the chatid at the bottom, which is why the value 64px is utilized. However, I encountered an error stating The function toggle3(); has not been defined. <div id="chat ...

In the case of a function with multiple necessary conditions, the decision to either proceed with the function or halt node progression

Before proceeding with the code below, I need to conduct an initial check on two conditions. If neither condition is met, I want Node.js to halt any further execution. Should I incorporate this as a check at the beginning of my code or wrap my main code wi ...

Tips for implementing ngChange within a personalized directive

Looking to create a directive for a toggle button, here is the code I want to include in the directive: <div class="toggle-button" ng-class="{true: toggleTrue === true, false: toggleTrue === false}"> <button class="true" ng-click="toggleTrue ...

Guide on removing material-ui from your project and updating to the newest version of MUI

I need to update my React app's material-ui package to the latest version. Can someone provide instructions on how to uninstall the old version and install the new MUI? UPDATED: In my package.json file, the current dependencies are listed as: ...

Modify the way the menu functions using only CSS or Javascript

Looking to update a menu using only CSS or JavaScript. The menu is designed for an e-commerce website, featuring categories with collapsed subcategories. I'd like the sub-categories to automatically expand when the page loads, eliminating the need fo ...

How to extract a substring from a string in Javascript

I am currently facing an issue with extracting a specific part of a string (from the URL pathname) and I need some help to solve it. Here is what I have tried so far: ^(/svc_2/pub/(.*?).php) The string in question is: /svc_2/pub/stats/dashboard.php?aja ...

I am attempting to update the URL of an iframe dynamically, but I am encountering an issue: the Error message stating that an Unsafe value is being

Currently, I am attempting to dynamically alter the src of an iframe using Angular 2. Here is what I have tried: HTML <iframe class="controls" width="580" height="780" src="{{controllerSrc}}" frameborder="0" allowfullscreen></iframe> COMPONE ...

Combining an array of JSON maps using JQ and specific key values

My JSON data has the following structure: [ { "100": "ONE", "200": "TWO" }, { "100": "1", "200": "2" } ] The expected output should look like this: { ...

Sorting in Ag-grid is not functioning as intended for AM/PM time formats

My goal is to display a list of schedules in either ascending or descending order. While Ag-grid provides default sorting, it doesn't align with my desired outcome after formatting the times into AM/PM format (for instance, 01:00 PM appearing before 1 ...

Directly convert data from MongoDB result to JSON without the need to deserialize it into a struct in Golang

Can you directly convert an mgo result to a JSON byte array without needing to serialize it into a slice of structs beforehand? ...

unable to choose the radio option

Encountering an unusual problem with the radio buttons due to custom styling. The issue arises when trying to select certain options. Here is the jsfiddle link for reference: http://jsfiddle.net/bm6Lfhdz/1/ Attempt to choose 'Yes' from the secon ...

The json filter encounters an error of `NoMethodError: undefined method '[]' for nil:NilClass`

When processing entries from a logfile that contains both plain text and JSON formatted messages, I initially used grep to filter messages enclosed in curly braces for further processing with a chained filter. While grep worked well for plain messages, the ...

execute the $scope.watch function only when the field loses focus

I am new to Angular and I am searching for a method to trigger a function only after the focus is out of the field, rather than after every change. The purpose of this function is to check if the user has modified the data in a specific <td> element, ...