object array Group by an element?

前端 未结 5 1019
面向向阳花
面向向阳花 2020-12-30 14:42

Please see this example: JsFiddle

Question: I have the following JSON Array

y= [ {\"LngTrend\":15,\"DblValue\":10,\"DtmStamp\":13582260         


        
5条回答
  •  臣服心动
    2020-12-30 15:13

    You should use a hash. A hash will allow you to easily index all of the DblValue values by DtmStamp. Here is a full working example:

    jsFiddle

    var y = [ {"LngTrend":15,"DblValue":10,"DtmStamp":1358226000000},     
    {"LngTrend":16,"DblValue":92,"DtmStamp":1358226000000},    
    {"LngTrend":17,"DblValue":45,"DtmStamp":1358226000000},
    {"LngTrend":18,"DblValue":87,"DtmStamp":1358226000000},
    {"LngTrend":15,"DblValue":10,"DtmStamp":1358226060000},
    {"LngTrend":16,"DblValue":87,"DtmStamp":1358226060000},
    {"LngTrend":17,"DblValue":45,"DtmStamp":1358226060000},
    {"LngTrend":18,"DblValue":92,"DtmStamp":1358226060000} ];
    
    var x = {};
    
    var i = 0;
    while(i++ < y.length) {
        var key = y[i].DtmStamp.toString();
        if (typeof(x[key]) == "undefined") x[key] = [];
        x[key].push(y[i].DblValue);
    }
    
    alert(JSON.stringify(x));
    

    The key is to use a hash on the values you want to group by.

    Result:

    {
        "1358226060000": [
            92,
            45,
            87,
            10
        ],
        "1358226000000": [
            87,
            45,
            92,
            10
        ]
    }
    

    If you want to prevent duplicates, you can do so by adding if/then logic in conjunction with indexOf().

提交回复
热议问题