简体   繁体   English

如何使用JavaScript在现有JSON对象中添加新的键值对?

[英]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 我需要在workbookInformation下添加新的密钥对

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" 添加新密钥但我希望它在“workbookInformation”下

There are two ways for adding new key value pair to Json Object in JS 在JS中有两种方法可以将新的键值对添加到Json Object中

var jsObj = {
    "workbookInformation": {
        "version": "9.1",
        "source-platform": "win"
    },
    "datasources1": {

    },
    "datasources2": {

    }
}

1.Add New Property using dot(.) 1.使用点(。)添加新属性

jsObj.workbookInformation.NewPropertyName ="Value of New Property"; 

2.Add New Property specifying index like in an arrays . 2.在数组中添加指定索引的新属性。

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 - 如果你想为json对象的每个键添加新的键和值,然后你可以使用以下代码,你可以使用其他答案的代码 -

Object.keys(json).map(
  function(object){
    json[object]["newKey"]='newValue'
});

Your object is only a JavaScript object and not JSON. 您的对象只是一个JavaScript对象而不是JSON。 You can either use brackets notation or the dot notation like 您可以使用brackets notation或点符号表示

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. 如果你有JSON数组对象而不是简单的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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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