[英]Reduce Single Array of Objects using two properties of an Object
I have a single array of objects and I would like to reduce it down to another array of objects based on two keys value pairs.我有一个对象数组,我想将它缩减为基于两个键值对的另一个对象数组。
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
}
];
Should be transformed into:应该改成:
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
},
];
Tired using map and reduce and even lodash.厌倦了使用 map 和 reduce 甚至 lodash。 However, all my attempts were futile.然而,我所有的尝试都是徒劳的。
Using Array.reduce
, you can group the objects by key1
and key2
value pairs.使用Array.reduce
,您可以按key1
和key2
值对对对象进行分组。 And the variable groupBy
object values contain the result you want and you can generate the values only using Object.values(groupBy)
.变量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);
Using Array.prototype.reduce()
, build up a Map
of entries, keyed by the combination of any key*
properties while merging in the other properties.使用Array.prototype.reduce()
构建一个条目Map
,由任何key*
属性的组合键控,同时合并其他属性。
Then you can convert the Map
values into a new array然后您可以将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.