How to add a new key value pair in existing JSON object using JavaScript?
var json = {
"workbookInformation": {
"version": "9.1",
"source-platform": "win"
},
"datasources1": {
...
},
"datasources2": {
...
}
}
I need to add new key pair under workbookInformation
like
var json={
"workbookInformation": {
"version": "9.1",
"source-platform": "win",
"new_key":"new_value"
},
"datasources1": {
...
},
"datasources2": {
...
}
}
json['new_key'] = 'new_value';
adds the new key but I want it under “workbookInformation”
There are two ways for adding new key value pair to Json Object in JS
var jsObj = {
"workbookInformation": {
"version": "9.1",
"source-platform": "win"
},
"datasources1": {
},
"datasources2": {
}
}
1.Add New Property using dot(.)
jsObj.workbookInformation.NewPropertyName ="Value of New Property";
2.Add New Property specifying index like in an arrays .
jsObj["workbookInformation"]["NewPropertyName"] ="Value of New Property";
Finally
json = JSON.stringify(jsObj);
console.log(json)
If you want to add new key and value to each of the key of json object and then you can use the following code else you can use the code of other answers –
Object.keys(json).map(
function(object){
json[object]["newKey"]='newValue'
});
const Districts=[
{
"District": "Gorkha",
"Headquarters": "Gorkha",
"Area": "3,610",
"Population": "271,061"
},
{
"District": "Lamjung",
"Headquarters": "Besisahar",
"Area": "1,692",
"Population": "167,724"
}
]
Districts.map(i=>i.Country="Nepal")
console.log(Districts)
If you have JSON Array Object Instead of a simple JSON.
const Districts= [
{
"District": "Gorkha",
"Headquarters": "Gorkha",
"Area": "3,610",
"Population": "271,061"
},
{
"District": "Lamjung",
"Headquarters": "Besisahar",
"Area": "1,692",
"Population": "167,724"
}
]
Then you can map through it to add new keys.
Districts.map(i=>i.Country="Nepal");
Your object is only a JavaScript object and not JSON. You can either use brackets notation
or the dot notation like
json["workbookInformation"]["new_key"] = "new_value";
var json={
"workbookInformation": {
"version": "9.1",
"source-platform": "win"
}
}
json.workbookInformation.new_key = 'new_value';
console.log(json);
This should work:
json.workbookInformation.new_key = 'new_value';
json.workbookInformation.key = value;
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .