输入-
[
{color:'red', shape:'circle', size:'medium'},
{color:'red', shape:'circle', size:'small'}
]
输出-
[
{color:'red', shape:'circle', size:['medium','small']}
]
如何用Java语言实现?
答案 0 :(得分:1)
您可以创建一个通用函数,该函数将对象数组和键数组作为参数进行匹配。
您可以按照以下步骤进行操作:
reduce()
并将累加器设置为空数组[]
filter()
上使用Object.keys()
获取其他道具(唯一道具)forEach()
键并将值推入相应的数组。reduce()
const arr = [
{color:'red', shape:'circle', size:'medium'},
{color:'red', shape:'circle', size:'small'}
]
function groupByProps(arr,props){
const res = arr.reduce((ac,a) => {
let ind = ac.findIndex(b => props.every(k => a[k] === b[k]));
let others = Object.keys(a).filter(x => !props.includes(x));
if(ind === -1){
ac.push({...a});
others.forEach(x => ac[ac.length - 1][x] = []);
ind = ac.length - 1
}
others.forEach(x => ac[ind][x].push(a[x]));
return ac;
},[])
return res;
}
const res = groupByProps(arr,['color','shape'])
console.log(res)
答案 1 :(得分:1)
如果您只想根据color
和shape
进行分组,则可以使用reduce
。创建一个累加器对象,将这两个属性的每个唯一组合用|
分隔为键。并将您要在输出中的对象作为它们的值。然后使用Object.values()
将这些对象作为数组获取。
const input = [
{color:'red', shape:'circle', size :'medium'},
{color:'red', shape:'circle', size:'small'},
{color:'blue', shape:'square', size:'small'}
];
const merged = input.reduce((acc, { color, shape, size }) => {
const key = color + "|" + shape;
acc[key] = acc[key] || { color, shape, size: [] };
acc[key].size.push(size);
return acc
}, {})
console.log(Object.values(merged))
这是合并/累加器的样子:
{
"red|circle": {
"color": "red",
"shape": "circle",
"size": [
"medium",
"small"
]
},
"blue|square": {
"color": "blue",
"shape": "square",
"size": [
"small"
]
}
}
您可以通过创建要分组的键数组来使其动态:
const input = [
{ color: 'red', shape: 'circle', size: 'medium' },
{ color: 'red', shape: 'circle', size: 'small' },
{ color: 'blue', shape: 'square', size: 'small' }
];
const groupKeys = ['color', 'shape'];
const merged = input.reduce((acc, o) => {
const key = groupKeys.map(k => o[k]).join("|");
if (!acc[key]) {
acc[key] = groupKeys.reduce((r, k) => ({ ...r, [k]: o[k] }), {});
acc[key].size = []
}
acc[key].size.push(o.size)
return acc
}, {})
console.log(Object.values(merged))
答案 2 :(得分:1)
这是一个简单的groupBy
函数,它接受对象数组和props
数组进行分组:
let data = [
{color:'red', shape:'circle', size:'medium'},
{color:'red', shape:'circle', size:'small'}
]
let groupBy = (arr, props) => Object.values(arr.reduce((r,c) => {
let key = props.reduce((a,k) => `${a}${c[k]}`, '')
let otherKeys = Object.keys(c).filter(k => !props.includes(k))
r[key] = r[key] || {...c, ...otherKeys.reduce((a,k) => (a[k] = [], a),{})}
otherKeys.forEach(k => r[key][k].push(c[k]))
return r
}, {}))
console.log(groupBy(data, ['color','shape']))
想法是使用Array.reduce并基本上创建传入的props的字符串键。对于其他字段,请创建一个数组,并在每次迭代时继续在其中推送值。