如何使用动态密钥更新JSON数组

时间:2016-07-07 10:10:33

标签: javascript arrays json

我想用数组的动态对象更新现有密钥,我该怎么做

var groupData = [
  {
    "Logon": 0,
    "Logon": 1
  }, {
    "Logoff": 0
  }, {
    "Special Logon": 0
  }, {
    "Other System Events": 0
  }, {
    "System Integrity": 0
  }, {
    "Other Logon/Logoff Events": 0
  }, {
    "Security State Change": 0
  }, {
    "Audit Policy Change": 0
  }, {
    "Security Group Management": 0
  }
];

var key = logon;
var val = 10;
groupData[0].key = val;

4 个答案:

答案 0 :(得分:3)

您需要使用[]表示法,因为您需要key内的值,而不是key本身:

groupData[0][key] = val;

图例:

Object[key]; // Value of key index in Object.
Object.key;  // "key" index in Object.

另外,看起来你需要更换:

var key = "Logon";

答案 1 :(得分:1)

尝试以下方法:

var key = logon;
var val = 10;
groupData[0].key = val;

进入

var key = "Logon";
var val = 10;
groupData[0][key] = val;

答案 2 :(得分:1)

我认为你的意思是

key = 'Logon';
val = 10;
groupData[0][key] = val;

答案 3 :(得分:0)

您可以尝试以下内容:

var key = 'Logon';
var val = 10;
groupData[0][key] = val;