我有这些值:
var firstHeader = $('#header0').text(); // 6KP
var secondHeader = $('#header1').text(); // 7KP
var thirdHeader = $('#header2').text(); // 8KP
var first = $('#input0').val(); // 77
var second = $('#input1').val(); //88
var third = $('#input2').val(); // 99
我需要创建一个JSON对象才能拥有它:
{6KP:77, 7KP:88, 8KP:99}
我试图这样做,但没有成功:
var data = { firstHeader: first, secondHeader: second, thirdHeader: third };
data = JSON.stringify(data, null, ' ');
我的回答是:
{firstHeader: 77, secondHeader:88, thirdHeader:99}
如何放置值而不是这些变量名?
答案 0 :(得分:5)
您使用数组表示法,例如
find
如果您使用的是ES6,则可以使用速记:
var data = {};
data[firstHeader] = first;
答案 1 :(得分:2)
您需要使用方括号将变量值评估为键名:
var data = {};
data[firstHeader] = first;
data[secondHeader] = second;
data[thirdHeader] = third;
工作示例
var firstHeader = '6KP';
var secondHeader = '7KP';
var thirdHeader = '8KP';
var first = '77';
var second = '88';
var third = '99';
var data = {};
data[firstHeader] = first;
data[secondHeader] = second;
data[thirdHeader] = third;
console.log(JSON.stringify(data));
答案 2 :(得分:1)
替换行
var data = { firstHeader: first, secondHeader: second, thirdHeader: third };
使用
var data ={};
data[firstHeader]= first;
data[secondHeader]= second;
data[thirdHeader]: third ;