Javascript 对象数组 按元素分组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14592799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:19:34  来源:igfitidea点击:

object array Group by an element?

javascriptjquery

提问by Mina Gabriel

Please see this example: JsFiddle

请看这个例子:JsFiddle

Question: I have the following JSON Array

问题:我有以下几点 JSON Array

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} ]

I was trying to group these object by DtmStampend up having something like this :

我试图通过DtmStamp最终得到这样的东西来对这些对象进行分组:

 x =  [[1358226000000,10,92,45,87],[1358226060000,10,87,45,92], .......]

In other words:

换句话说:

x[0][0] = y[0].DtmStamp ;
x[0][1] = y[0].LngTrend ;
x[0][2] = y[1].LngTrend ;
x[0][3] = y[2].LngTrend ; 
x[0][4] = y[3].LngTrend ;

Unfortunately, it ends with something I don't want.

不幸的是,它以我不想要的东西结束。

Here is what I have tried so far:

这是我迄今为止尝试过的:

   var dataTrendArray = [];
           $.each(x, function (index, value) {
                var trendArray = [];
                if (index % 4 == 0) {
                    trendArray.push(x[index].DtmStamp);
                    for (var i = 0; i < 4; i++) {
                        index = eval(index + i);
                        trendArray.push(x[index].DblValue);
                    }
                }

               console.log(trendArray) ;
                dataTrendArray.push(trendArray);
            });

Can someone help me get on the right path?

有人可以帮助我走上正确的道路吗?

回答by crush

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.

您可以将 JavaScript 对象用作类似于地图的键/值数据结构。属性名称将作为键,而属性值将作为值。这将允许您分组。

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.

回答by Elliot B.

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

您应该使用hash。散列将允许您轻松地按 索引所有DblValueDtmStamp。这是一个完整的工作示例:

jsFiddle

js小提琴

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/thenlogic in conjunction with indexOf().

如果您想防止重复,您可以通过添加if/thenindexOf().

回答by Bergi

Your code pushes empty trendArrays even if they are not filled (index % 4 != 0). Instead, use this:

trendArray即使它们未填充 ( index % 4 != 0),您的代码也会推送空s 。相反,使用这个:

var dataTrendArray = [];
for (var i = 0; i < x.length; i += 4) {
    var trendArray = [ x[i].DtmStamp ];
    for (var j = i, l = Math.max(i + 4, x.length); j < l; j++) {
        trendArray.push(x[j].DblValue);
    }
    // console.log(trendArray) ;
     dataTrendArray.push(trendArray);
}

However, it might fit better if you just grouped the trendArrays into an object, using the DtmStampas keys:

但是,如果您只是使用DtmStampas 键将趋势数组分组到一个对象中,它可能更适合:

var dataTrend = {};
for (var i=0; i<x.length; i++) {
    var key = x[i].DtmStamp;
    if (key in dataTrend)
        dataTrend[key].push(x[i].DblValue);
    else
        dataTrend[key] = [ x[i].DblValue ];
}

回答by Beetroot-Beetroot

You can build a sparse array, indexed by DtmStamp.

您可以构建一个由 DtmStamp 索引的稀疏数组。

var x = [];
$.each(y, function(i, obj) {
    var s = obj.DtmStamp;
    if(!x[s]) x[s] = [];
    x[s].push(obj.DblValue);
});

//x is now a sparse array, indexed by DtmStamp

This has the advantage over an object, that the array elements are in DtmStamp order.

这比对象具有优势,即数组元素按 DtmStamp 顺序排列。

//To loop through x
for(i in x) {
    ...
}

回答by user3772857

 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 k in y){
  if(x[y[k]["DtmStamp"]] == undefined)
     x[y[k]["DtmStamp"]] = [];
     x[y[k]["DtmStamp"]].push(y[k]["DblValue"])
}
alert(JSON.stringify(x))
console.log(x);

See http://plnkr.co/edit/511sKSdzHGYuvpYqKCPD?p=preview

http://plnkr.co/edit/511sKSdzHGYuvpYqKCPD?p=preview