2017-06-06 52 views
0

大家好我使用的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} ] 
+2

預期結果json? –

+1

一,二,三會發生什麼? –

+0

預期結果json數組@JinsPeter – jose

回答

2

可以使用哈希表和陣列作爲對象的靜態鍵來使用動態方法。

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

+0

它在IE – jose

+0

工作在IE中。 –

+0

staticKeys是組值右側 – jose

1

這裏是一個代碼片段,對我的工作,

它assums你知道對象的關鍵屬性

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); 

希望它幫助;)

關於。

+0

試着做一個小提琴@fxlacroix – jose

+0

這裏是https://jsfiddle.net/5mvvxuLk/ – fxlacroix

1

你可以試試這個片段,「ouput」​​變量包含結果;

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);