Michael Ardan Michael Ardan - 1 year ago 56
JSON Question

JavaScript - Pushing JSON Object Using Value as Element Name

I'm trying to push an object inside an array with dynamic attribute name.

Let's say we have the following variables defined

myJSON = {"students" : [ {"name":"Your Name"}, {"name":"My Name"} ] };

attribName = "name";

myValue = "myValue";

parsedJSON = JSON.parse(myJSON);

parsedJSON["students"].push({attribName : myValue});

myJSON = JSON.stringfy(parsedJSON);

The example isn't working. Is there a way to push an object with dynamic attribute name?

Answer Source

From MDN,

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).

Also note that input you has provided is object, not json

var myJSON = {
  "students": [{
    "name": "Your Name"
  }, {
    "name": "My Name"

var attribName = "name";

var myValue = "myValue";

var obj = {};
obj[attribName] = myValue;