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

T S*_*raj 8 javascript json

var json = {
    "workbookInformation": {
        "version": "9.1",
        "source-platform": "win"
    },
    "datasources1": {
        ...
    },
    "datasources2": {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要在添加新的密钥对workbookInformation

var json={
    "workbookInformation": {
         "version": "9.1",
         "source-platform": "win",
         "new_key":"new_value"
    },
    "datasources1": {
        ...
    },
    "datasources2": {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

json['new_key'] = 'new_value'; 添加新密钥但我希望它在"workbookInformation"下

Ari*_*gri 17

在JS中有两种方法可以将新的键值对添加到Json Object中

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

    },
    "datasources2": {

    }
}
Run Code Online (Sandbox Code Playgroud)

1.使用点(.)添加新属性

jsObj.workbookInformation.NewPropertyName ="Value of New Property"; 
Run Code Online (Sandbox Code Playgroud)

2.在数组中添加指定索引的新属性.

jsObj["workbookInformation"]["NewPropertyName"] ="Value of New Property"; 
Run Code Online (Sandbox Code Playgroud)

最后

 json = JSON.stringify(jsObj);
 console.log(json)
Run Code Online (Sandbox Code Playgroud)


Ayu*_*rma 8

如果您想为 json 对象的每个键添加新的键和值,然后您可以使用以下代码,否则您可以使用其他答案的代码 -

Object.keys(json).map(
  function(object){
    json[object]["newKey"]='newValue'
});
Run Code Online (Sandbox Code Playgroud)


小智 5

 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)
Run Code Online (Sandbox Code Playgroud)

如果您有 JSON 数组对象而不是简单的 JSON。

const Districts= [
  {
    "District": "Gorkha",
    "Headquarters": "Gorkha",
    "Area": "3,610",
    "Population": "271,061"
  },
  {
    "District": "Lamjung",
    "Headquarters": "Besisahar",
    "Area": "1,692",
    "Population": "167,724"
  }
]
Run Code Online (Sandbox Code Playgroud)

然后您可以通过它进行映射以添加新键。

Districts.map(i=>i.Country="Nepal");
Run Code Online (Sandbox Code Playgroud)