如果元素键是变量,如何将元素添加到多维JSON数组

时间:2018-07-31 12:47:20

标签: javascript json

有一个JSON文件,其数组类似

{
    "general_array":[
        {"key_1":["a","b","c"]}
    ]
}

我想在数组中添加一个元素,例如

{"key_2":["d","e","f"]}

但是我从变量等得到的新密钥的值。

var newKey = 'key_2';

我正尝试将元素添加到现有数组中,如下所示

// ... getting file content
// var jsonFileContent = '{"general_array":[{"key_1":["a","b","c"]}]}';

var jsonObj = JSON.parse(jsonFileContent);

var newKey = 'key_2';

jsonObj.general_array.push({newKey:['d','e','f']});

var newJsonFileContent = JSON.stringify(jsonObj);

// and rewrite the file ...
// console.log(newJsonFileContent);

但是在文件中我得到了

{
    "general_array":[
        {"key_1":["a","b","c"]},
        {"newKey":["d","e","f"]}
    ]
}

即作为新的元素键,我得到了变量的名称,但是我需要它的值

如何增加价值?


已更新

使用[newKey]的解决方案可在大多数浏览器中使用,但不适用于Internet Explorer 11

我也需要在IE11中也可以使用的解决方案,因此问题仍然存在

3 个答案:

答案 0 :(得分:4)

您可以使用[newKey]来获取变量的值作为键名:

var jsonFileContent = `
{
    "general_array":[
        {"key_1":["a","b","c"]}
    ]
}`;
var jsonObj = JSON.parse(jsonFileContent);

var newKey = 'key_2';

var tempObj = {};
tempObj[newKey] = ['d','e','f'];
jsonObj.general_array.push(tempObj);

var newJsonFileContent = JSON.stringify(jsonObj);
console.log(newJsonFileContent);

答案 1 :(得分:2)

要将变量的值用作JSON键,请将其括在方括号中,如下所示:

{[newKey]:['d','e','f']}

let jsonFileContent = '{"general_array":[{"key_1":["a","b","c"]}]}';

let jsonObj = JSON.parse(jsonFileContent);

let newKey = 'key_2';

jsonObj.general_array.push({[newKey]:['d','e','f']});

let newJsonFileContent = JSON.stringify(jsonObj);

console.log(newJsonFileContent)

这是computed property name syntax。这是someObject[someKey] = somevalue

的速记/语法加注

答案 2 :(得分:2)

尝试更改此行:

var newObj = {};
newObj[newKey] = ['d','e','f'];
jsonObj.general_array.push(newObj);

为此:

{{1}}