2

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?

1
  • 1
    This is not a question Commented Aug 16, 2016 at 9:53

3 Answers 3

5

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;
myJSON["students"].push(obj);
console.log(myJSON);

Sign up to request clarification or add additional context in comments.

Comments

2
function(key, value, json) {

  var obj = {};
  obj[key] = value;
  json['students'].push(obj);

  return arr;
}

Comments

0

You can also do the modification in your code :

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

attribName = "name";

myValue = "myValue123";

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

console.log(myJSON);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.