结合JSON属性和总和值

时间:2014-10-30 18:49:52

标签: javascript json

我有这样的事情:

[
    {
        "SalesRep": "Bob",
        "Market": "Market1",
        "Revenue": "1000"
    },
    {
        "SalesRep": "Mary",
        "Market": "Market2",
        "Revenue": "2000"
    },
    {
        "SalesRep": "Amy",
        "Market": "Market1",
        "Revenue": "3000"
    },
    {
        "SalesRep": "Cody",
        "Market": "Market2",
        "Revenue": "5000"
    }
]

而我想要获得的是另一个与市场相结合并将收入相加的对象,因此上述内容将是:

[
    {
        "Market": "Market1",
        "Revenue": "4000"
    },
    {
        "Market": "Market2",
        "Revenue": "7000"
    }
]

我无法弄清楚如何迭代topMarkets来搜索市场是否存在于内部。我尝试了很多不同的东西,但这可能是我最接近的。

var topMarkets = [];
$.each( data, function( k, v ) {

    for(var i=0; i<data.length; i++) {
         if (topMarkets.length == 0) {
             topMarkets.push({"Market":v.Market, "Revenue":parseFloat(v.Revenue)});
         } else {
             //how to check if topMarkets[i]["Market"] == v.Market ?
             //push to topMarkets here if v.Market does not exist in topMarkets
         }
    }

});

1 个答案:

答案 0 :(得分:1)

只需迭代并检查!

var totalRevenues = [];
for (var i = 0; i < data.length; i++) {
    var market = data[i].Market;
    var index = getMarketIndex(totalRevenues, market);
    var revenue = parseInt(data[i].Revenue, 10);

    if (index != -1) {  
        totalRevenues[index].Revenue += revenue;
    } else {
        totalRevenues.push({Market: market, Revenue: revenue});
    }
}

function getMarketIndex(array, market) {
    for (var i = 0; i < array.length; i++) {
        if (array[i].Market == market) {
            return i;
        }
    }

    return -1;
}

工作演示:http://jsfiddle.net/hcgawe3p/