簡體   English   中英

如何使用Lodash在特定字段上的JavaScript對象數組進行分組?

[英]How to group an array of objects in JavaScript on specific fields using Lodash?

編輯:我認為這是一個比簡單的_.groupBy不同的問題,因為我試圖按所有鍵進行分組並返回哈希圖而不是數組。


我有以下對象的數組:

items = [
  { created_at: "01/01/2016", name: "bob", age: 21, height: 60 },
  { created_at: "01/02/2016", age: 22, height: 70 },
  { created_at: "01/03/2016", name: "alice", age: 23 }
]

我正在嘗試將其轉換為以下格式:

{
  "name": [
    {
      "value": "bob",
      "created_at": "01/01/2016"
    },
    {
      "value": "alice",
      "created_at": "01/03/2016"
    }
  ],
  "age": [
    {
      "value": 21,
      "created_at": "01/01/2016"
    },
    {
      "value": 22,
      "created_at": "01/02/2016"
    },
    {
      "value": 23,
      "created_at": "01/03/2016"
    }
  ],
  "height": [
    {
      "value": 60,
      "created_at": "01/01/2016"
    },
    {
      "value": 70,
      "created_at": "01/02/2016"
    }
  ]
}

我的要求是我忽略了created_at字段,但將其他所有內容分組。

一種解決方案是:

 var items = [ { created_at: "01/01/2016", name: "bob", age: 21, height: 60 }, { created_at: "01/02/2016", age: 22, height: 70 }, { created_at: "01/03/2016", name: "alice", age: 23 } ] var store = {} for(var i=0; i < items.length; i++) { var item = items[i] for(key in item) { if(key === "created_at") { continue } value = item[key] if(!store[key]) { store[key] = [] } store[key].push({ value: value, created_at: item.created_at }) } } $('pre').text(JSON.stringify(store, null, 2)) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body><pre></pre></body> 

我想知道是否有一些很酷的方法可以在lodash使用它……也許使用.map().groupBy()東西? 我不太了解如何正確使用它們,而是試圖學習新的,更優雅的代碼編寫方法。

使用reduce可能是最短的方法。

var baseKey = 'created_at';

var result = items.reduce(function(col, item) {
  Object.keys(item).forEach(function(key) {
    if (key === baseKey || !item[key]) return;
    var o = { value: item[key] };
    o[baseKey] = item[baseKey];
    (col[key] = col[key] || []).push(o);
  });
  return col;
}, {});

JSFiddle演示: https ://jsfiddle.net/pLcv1am2/6/

您是專門詢問lodash的,所以此答案是使用lodash構造的。

注意我正在使用_.chain方法-這使鏈接多個操作而不是分別單獨運行它們很方便。

一種非常接近(不完美)的方式(我敢肯定還有很多其他方式)是這樣的:

items = _.chain(items)
  .map(function(n) {
    var created = _.get(n, 'created_at');
    var arr = [];
    _.each(n, function(n, k) {
      if (k != 'created_at') {
        arr.push({
          'field': k,
          'value': n,
          'created_at': created
        });
      }
    });
    return arr;
  })
  .flatten()
  .groupBy('field')
  .value();

結果是一個看起來像這樣的集合:

{ "name": 
    [ 
        { "field": "name", "value": "bob", "created_at": "01/01/2016" }, 
        { "field": "name", "value": "alice", "created_at": "01/03/2016" } 
    ], 
  "age": [
     ....

這是一個玩弄此代碼的小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM