[英]Reduce Single Array of Objects using two properties of an Object
我有一個對象數組,我想將它縮減為基於兩個鍵值對的另一個對象數組。
const original =
[
{
key1: 'a',
key2: 'AA',
value: 1
},
{
key1: 'a',
key2: 'AA',
anotherValue: 2
},
{
key1: 'b',
key2: 'BB',
value: 1
},
{
key1: 'a',
key2: 'AA',
yetAnother: 3
},
{
key1: 'b',
key2: 'BB',
anotherValue: 4
},
{
key1: 'c',
key2: 'CC',
value: 1
}
];
應該改成:
const result =
[
{
key1: 'a',
key2: 'AA',
value: 1,
anotherValue: 2,
yetAnother: 3
},
{
key1: 'b',
key2: 'BB',
value: 1,
anotherValue: 4
},
{
key1: 'c',
key2: 'CC',
value: 1
},
];
厭倦了使用 map 和 reduce 甚至 lodash。 然而,我所有的嘗試都是徒勞的。
使用Array.reduce
,您可以按key1
和key2
值對對對象進行分組。 變量groupBy
對象值包含您想要的結果,您只能使用Object.values(groupBy)
生成值。
const original = [ { key1: 'a', key2: 'AA', value: 1 }, { key1: 'a', key2: 'AA', anotherValue: 2 }, { key1: 'b', key2: 'BB', value: 1 }, { key1: 'a', key2: 'AA', yetAnother: 3 }, { key1: 'b', key2: 'BB', anotherValue: 4 }, { key1: 'c', key2: 'CC', value: 1 } ]; const groupBy = original.reduce((acc, cur) => { const { key1, key2, ...rest } = cur; const key = key1 + "_" + key2; acc[key] ? acc[key] = { ...acc[key], ...rest } : acc[key] = cur; return acc; }, {}); const result = Object.values(groupBy); console.log(result);
使用Array.prototype.reduce()
構建一個條目Map
,由任何key*
屬性的組合鍵控,同時合並其他屬性。
然后您可以將Map
值轉換為新數組
const original = [{"key1":"a","key2":"AA","value":1},{"key1":"a","key2":"AA","anotherValue":2},{"key1":"b","key2":"BB","value":1},{"key1":"a","key2":"AA","yetAnother":3},{"key1":"b","key2":"BB","anotherValue":4},{"key1":"c","key2":"CC","value":1}] const t1 = performance.now() const result = [...original.reduce((map, obj) => { // create a key from all the "key*" properties const key = Object.keys(obj) .filter(key => key.startsWith("key")) .sort() .map(key => obj[key]).join(":") // looks like "a:AA", "b:BB", etc // merge with previously found matches const entry = { ...(map.get(key) ?? {}), ...obj } // collect the merged object return map.set(key, entry) }, new Map()).values()] const t2 = performance.now() console.info(result, `in ${t2 - t1}ms`)
.as-console-wrapper { max-height: 100% !important; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.