how to add key value pair in the JSON object already declared
Could you do the following:
obj = {
"1":"aa",
"2":"bb"
};
var newNum = "3";
var newVal = "cc";
obj[newNum] = newVal;
alert(obj["3"]); // this would alert 'cc'
Object assign copies one or more source objects to the target object. So we could use Object.assign
here.
Syntax: Object.assign(target, ...sources)
var obj = {};
Object.assign(obj, {"1":"aa", "2":"bb"})
console.log(obj)
You can use dot notation or bracket notation ...
var obj = {};
obj = {
"1": "aa",
"2": "bb"
};
obj.another = "valuehere";
obj["3"] = "cc";