簡體   English   中英

如何按鍵對一組對象進行分組?

[英]How to group an array of objects by key?

如何通過對象鍵對對象數組進行分組以基於分組創建新的對象數組? 例如,我有一個汽車對象數組:

const array = [
  {red: [ {height: 50} ]},
  {green: [ {height: 20} ]},
  {blue: [ {height: 30} ]},
  {blue: [ {height: 40} ]},
  {red: [ {height: 10} ]},
  {green: [ {height: 60} ]}
]

我想創建一個新的對象數組。(關鍵是顏色)

const result = [
  {red: [{height: 50}, {height: 10}]},
  {green: [{height: 20}, {height: 60}]},
  {blue: [{height: 30}, {height: 40}]}
]

我嘗試使用 lodash.groupBy,但是我根本不知道如何解決這個問題。

使用 array reduce 可以迭代數據並計算結果對象。

 const array = [ { 'red': [ { height: 50 } ] }, { 'green': [ { height: 20 } ] }, { 'blue': [ { height: 30 } ] }, { 'blue': [ { height: 40 } ] }, { 'red': [ { height: 10 } ] }, { 'green': [ { height: 60 } ] } ]; const res = array.reduce((acc, element) => { // Extract key and height value array const [key, heightValue] = Object.entries(element)[0]; // Get or create if non-exist, and push height value from array, index 0 (acc[key] || (acc[key] = [])).push(heightValue[0]); return acc; }, {}); console.log(res);

您可以使用 lodash 的_.mergeWith()將具有相同鍵的對象組合在一起,然后使用_.map()將其轉換回數組:

 const array = [{"red":[{"height":50}]},{"green":[{"height":20}]},{"blue":[{"height":30}]},{"blue":[{"height":40}]},{"red":[{"height":10}]},{"green":[{"height":60}]}] const fn = _.flow([ arr => _.mergeWith({}, ...arr, (o, s) => _.isArray(o) ? o.concat(s) : s), objs => _.map(objs, (v, k) => ({ [k]: v })) ]) const result = fn(array) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

暫無
暫無

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

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