繁体   English   中英

如何在javascript中动态按数组值分组

[英]how to group by the array values dynamically in javascript

嗨,我正在使用JavaScript,我有一组数组,我需要按对象分组

 var data = [{BuildingID: "5", FloorId: "65", one: 12, two: 15,three: 12},
            {BuildingID: "5", FloorId: "65", one: 12, two: 15,three: 12},
            {BuildingID: "6", FloorId: "65", one: 12, two: 15,three: 12},
            {BuildingID: "6", FloorId: "65", one: 12, two: 15,three: 12}]

我正在尝试按BuildingID进行分组,添加一,二,三注意:一二三不是静态的

预期输出

  var data = [{BuildingID: "5", FloorId: "65", one: 24, two: 30,three: 24},
              {BuildingID: "6", FloorId: "65", one: 24, two: 30,three: 24} ]

您可以通过使用哈希表和对象的静态键数组来使用动态方法。

 var data = [{ BuildingID: "5", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "5", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "6", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "6", FloorId: "65", one: 12, two: 15, three: 12 }], staticKeys = ['BuildingID', 'FloorId'] , grouped = data.reduce(function (hash) { return function (r, a) { var key = a[staticKeys[0]]; if (!hash[key]) { hash[key] = {}; staticKeys.forEach(function (k) { hash[key][k] = a[k]; }); r.push(hash[key]); } Object.keys(a).forEach(function (k) { if (staticKeys.indexOf(k) === -1) { hash[key][k] = (hash[key][k] || 0) + a[k]; } }); return r; }; }(Object.create(null)), []); console.log(grouped); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

这是一个对我有用的代码片段,

假设您知道对象的关键属性

var arr = [ { id: 1, name: 'bob' }, { id: 1, name: 'bill' }, { id: 1, name: 'bill' } ]

var noDuplicate = [];
var unique = {};

$.each(arr, function(key, item) {

    if (! unique[item.id + "-" + item.name]) {
        noDuplicate.push(item);
        unique[item.id + "-" + item.name] = true;
    }
});

console.log(noDuplicate);

希望能帮助到你 ;)

问候。

您可以尝试使用此代码段,“输出”变量包含结果;

var data = [{ BuildingID: "5", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "5", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "6", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "6", FloorId: "65", one: 12, two: 15, three: 12 }]
var groupBy = function(input, key) {
   return input.reduce(function(list, x) {
     list[x[key]] = x;
     return list;
   }, {});
};
var grouped = groupBy(data, 'BuildingID'), output=[];
for ( var key in grouped ) { output[output.length] = grouped[key]; }
console.log(output);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM