简体   繁体   中英

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'
});

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); 

这应该工作:

json.workbookInformation.new_key = 'new_value';
json.workbookInformation.key = value;

  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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM