从JSON循环和提取值并推送到数组

时间:2017-08-04 10:50:00

标签: javascript angularjs arrays json

我有一个JSON文件,我需要在其中访问其中一个值,该值是包含许多键和值的对象,这些键是更多对象。像这样:

"lineChart": {
    "Fri Jul 28, 2017": {
        "renewalFee_EUR": 1165,
        "extensionFee_EUR": 0,
        "renewalFee_USD": 5941.5,
        "extensionFee_USD": 0,
        "processingFee_USD": 25,
        "expressFee_USD": 0,
        "urgentFee_USD": 0,
        "latePayPenalty_USD": 0,
        "fxRate": 5.1,
        "subTotal_USD": 5966.5
    },
    "Tue Aug 1, 2017": {
        "renewalFee_EUR": 1165,
        "extensionFee_EUR": 0,
        "renewalFee_USD": 2411.55,
        "extensionFee_USD": 0,
        "processingFee_USD": 25,
        "expressFee_USD": 0,
        "urgentFee_USD": 0,
        "latePayPenalty_USD": 0,
        "fxRate": 2.07,
        "subTotal_USD": 2436.55
    }
}

我已经能够将键值Fri Jul 28, 2017存储在一个数组中,该数组用于将数据传递给视图中的图表。这部分工作正常。

var caLine = vm.graph.lineChart; 
// THIS STORES THE RETURNED VALUE(GRAPH DATA) FROM A REST REQUEST
//IN MY ROUTER FOLDER (USING ANGULARJS) 

lineLabelArr = [];

for (var prop in caLine) {
    if (caLine.hasOwnProperty(prop)) {
        lineLabelArr.push(prop)
    }
}

vm.labels = lineLabelArr; //VM.LABELS IS UED TO BIND DATA TO THE CHART'S DIRECTIVES

我只需要JSON文件中subTotal_USD下的数据在我的图表中显示为数据。

问题

如何遍历lineChart对象中的每个属性,从subTotal_USD键中提取值,并将其存储在可用于在图表中显示数据的数组中?我觉得我比这更复杂。

2 个答案:

答案 0 :(得分:2)

您已经拥有一系列密钥,您可以使用forEachmapreduce等进行循环。

您可以使用map

从密钥数组中创建新数组

const lineChart = {"Fri Jul 28, 2017":{renewalFee_EUR:1165,extensionFee_EUR:0,renewalFee_USD:5941.5,extensionFee_USD:0,processingFee_USD:25,expressFee_USD:0,urgentFee_USD:0,latePayPenalty_USD:0,fxRate:5.1,subTotal_USD:5966.5},"Tue Aug 1, 2017":{renewalFee_EUR:1165,extensionFee_EUR:0,renewalFee_USD:2411.55,extensionFee_USD:0,processingFee_USD:25,expressFee_USD:0,urgentFee_USD:0,latePayPenalty_USD:0,fxRate:2.07,subTotal_USD:2436.55}};

const lineLabelArr = [];

for (var prop in lineChart) {
    if (lineChart.hasOwnProperty(prop)) {
        lineLabelArr.push(prop)
    }
}

console.log(
  lineLabelArr.map(key => lineChart[key].subTotal_USD)
);

当然,有很多方法可以循环对象的键。就个人而言,我更喜欢这样做一个循环:

const lineChart = {"Fri Jul 28, 2017":{renewalFee_EUR:1165,extensionFee_EUR:0,renewalFee_USD:5941.5,extensionFee_USD:0,processingFee_USD:25,expressFee_USD:0,urgentFee_USD:0,latePayPenalty_USD:0,fxRate:5.1,subTotal_USD:5966.5},"Tue Aug 1, 2017":{renewalFee_EUR:1165,extensionFee_EUR:0,renewalFee_USD:2411.55,extensionFee_USD:0,processingFee_USD:25,expressFee_USD:0,urgentFee_USD:0,latePayPenalty_USD:0,fxRate:2.07,subTotal_USD:2436.55}};

const labels = [];
const subTotals = [];

Object.keys(lineChart).forEach(day => {
  const dayData = lineChart[day];
  
  labels.push(day);
  subTotals.push(dayData.subTotal_USD);
});

console.log("Labels:", labels);
console.log("subTotals:", subTotals);

答案 1 :(得分:1)

for(var i = 0; i < caLine.length; i++) {
    var datObj = caLine[i];
    if (datObj != null) {
        var subTotoalUSD = datObj["subTotal_USD"];
    }
}