我正在为客户构建一个Web应用程序,我已经接近完成了,但是我需要一些帮助。
我需要帮助将JavaScript对象的KEY和VALUE转换为JSON字符串,以便我可以在图表中使用它。我使用的图表是ChartJS。
这就是我的数组的样子。
Object {full-time: Object, part-time: Object}
full-time: Object
Access: 1
Excel: 2
Facebook: 1
NoSQL: 1
PHP: 1
WebEX: 1
WordPress: 1
part-time: Object
.NET: 1
Adobe Photoshop: 1
Visual Basic: 1
WordPress: 1
XML: 1
我的最终目标是拥有一些像这样的变量,所以当我在主对象上运行$ .each时,我会在代码中使用它:
skillGraph[key]['labels'] = SOMETHING HERE (.push ??)
然后当我们控制记录每个变量时,它们看起来像这样:
skillGraph['part-time']['labels'] = [".NET","Adobe PhotoShop", "Visual Basic","WordPress", "XML"]
skillGraph['part-time']['values'] = [1,1,1,1,1]
这样我可以像这样调用ChartJS Graph:
var workerTypePT = {
labels : skillGraph['part-time']['labels'],
datasets : [
{
fillColor : "rgba(151,187,205,0.5)",
highlightFill : "rgba(151,187,205,0.75)",
data: skillGraph['part-time']['values']
}
]
}
我尝试了什么?
我已尝试在主对象上执行$ .each,然后对其中的键执行$ .each,这是我当前的代码。在{{}}内部是第一次迭代在控制台中看到的内容。
graphWorkerType = {};
$.each(skillCountPerType, function(key, value) {
console.log(key); {
{
full - time
}
}
console.log(value); {
{
Object {
PHP: 1,
NoSQL: 1,
WebEX: 1,
Facebook: 1,
WordPress: 1…
}
Access: 1
Excel: 2
Facebook: 1
NoSQL: 1
PHP: 1
WebEX: 1
WordPress: 1
}
}
$('#typeUser').append('<option value="' + key + '">' + key + '</option>');
skillsforGraph = JSON.stringify(skillCountPerType[value]);
console.log(skillsforGraph); {
{
{
"PHP": 1,
"NoSQL": 1,
"WebEX": 1,
"Facebook": 1,
"WordPress": 1,
"Excel": 2,
"Access": 1
}
}
}
graphWorkerType[key] = new Array();
$.each(value, function(key2, value2) {
graphWorkerType[key].push(key2);
});
console.log(graphWorkerType); {
{
Object {
full - time: Array[7], part - time: Array[5]
}
full - time: Array[7]
0: "PHP"
1: "NoSQL"
2: "WebEX"
3: "Facebook"
4: "WordPress"
5: "Excel"
6: "Access"
part - time: Array[5]
0: "WordPress"
1: "XML"
2: ".NET"
3: "Adobe Photoshop"
4: "Visual Basic"
}
}
});
答案 0 :(得分:0)
您可以使用JSON.stringify()
将javascript对象转换为json答案 1 :(得分:0)
修改此部分
graphWorkerType[key] = new Array();
$.each(value, function(key2, value2 ) {
graphWorkerType[key].push(key2);
});
与
graphWorkerType[key] = { labels: [], values: []};
$.each(value, function(key2, value2 ) {
graphWorkerType[key]['labels'].push(key2);
graphWorkerType[key]['values'].push(value2);
});
然后您可以将graphWorkerType对象传递给图表