object array Group by an element?

前端 未结 5 1025
面向向阳花
面向向阳花 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:10

    You can leverage JavaScript objects as a key/value data structure similar to a map. The property name will serve as the key, while the property value will serve as the value. This will allow you to group.

    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 = {};
    
    for (var i = 0; i < y.length; ++i) {
        var obj = y[i];
    
        //If a property for this DtmStamp does not exist yet, create
        if (x[obj.DtmStamp] === undefined)
            x[obj.DtmStamp] = [obj.DtmStamp]; //Assign a new array with the first element of DtmStamp.
    
        //x will always be the array corresponding to the current DtmStamp. Push a value the current value to it.
        x[obj.DtmStamp].push(obj.DblValue);
    }
    
    console.log(x); //x is now an object grouped by DtmStamp. You can easily turn it back into an array here.
    

提交回复
热议问题