解析Json数组推送JavaScript

时间:2019-02-12 05:02:52

标签: javascript push splice

我有Json Parse列表,需要推送每个类别列表。 例子:

    listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
  var categoryData = [];
  var values = [];
  for(var i=0;i<listChartPeriods.length;i++){
      categoryData.push(listChartPeriods.slice(0,1)[0]); //here need to push each date  
      values.push(listChartPeriods[i])
   }

预期投放:

categoryData=["2018-05-04","2018-05-11","2018-05-18","2018-05-25","2018-06-01"]

 values=[21807210.5028442,21807210.5028442,21807210.5028442]//each category values

3 个答案:

答案 0 :(得分:4)

只需使用Object.keys即可获取数组中的日期。

const listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = Object.keys(listChartPeriods);
console.log(categoryData);

答案 1 :(得分:3)

以下应为您完成工作。在处理对象时,for循环是您的朋友。

var listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = [];

for(var char in listChartPeriods){
	for(var i = 0; i < listChartPeriods[char].length; i++){
		categoryData.push(listChartPeriods[char][i]);
	}
}
console.log(categoryData);

编辑:只需阅读更新的问题,您只需要键名。您也可以在for循环中执行此操作。

for(var char in listChartPeriods){
	categoryData.push(char)
}
console.log(categoryData);

答案 2 :(得分:0)

解决方案如下:

 for (let date in listChartPeriods){
    categoryData.push(date);
    let [first] = listChartPeriods[date];
    values.push(first);
 }

categoryData = [“ 2018-05-04”,“ 2018-05-11”,“ 2018-05-18”,“ 2018-05-25”,“ 2018-06-01”]

值= [21807210.5028442、21807210.5028442、21807210.5028442、21807210.5028442、21807210.5028442]