我第一次使用JSON开发项目,但我需要从JSON文件中获取所有时间戳,以将其放入图表中的数组中,所有时间戳都显示在图表上。
JSON文件如下所示:
[
{
timestamp: "1541404800",
data: {
OK: {
count: "8",
percentage: "100"
},
NOK: {
count: 0,
percentage: 0
}
}
},
{
timestamp: "1541408400",
data: {
OK: {
count: "1",
percentage: "100"
},
NOK: {
count: 0,
percentage: 0
}
}
}
]
答案 0 :(得分:2)
您正在寻找的是功能map
。有关更多详细信息,请参见documentation。
例如:
var data = [
{
timestamp: '1541404800',
data: {
OK: {
count: '8',
percentage: '100'
},
NOK: {
count: 0,
percentage: 0
}
}
},
{
timestamp: '1541408400',
data: {
OK: {
count: '1',
percentage: '100'
},
NOK: {
count: 0,
percentage: 0
}
}
}
];
var timestamps = data.map(function(d) { return d.timestamp }));
答案 1 :(得分:0)
只需使用for
遍历数组即可获取数据
var json = [
{
timestamp: '1541404800',
data: {
OK: {
count: '8',
percentage: '100'
},
NOK: {
count: 0,
percentage: 0
}
}
},
{
timestamp: '1541408400',
data: {
OK: {
count: '1',
percentage: '100'
},
NOK: {
count: 0,
percentage: 0
}
}
}
];
var newArr = [];
for (var i = 0; i < json.length; i++) {
newArr.push(json[i].timestamp);
}
console.log(newArr); // ['1541404800','1541408400']