在此之前
const array = [
{ group: '1', tag: ['sins'] },
{ group: '1', tag: ['sun'] },
{ group: '2', tag: ['red'] },
{ group: '2', tag: ['blue'] },
{ group: '2', tag: ['black'] },
];之后
const array = [
{ group: '1', tag: ['sins', 'sun'] },
{ group: '2', tag: ['red', 'blue', 'black'] },
];我想像上面的和弦那样改变它。我想要有人创造一个很酷的和弦。
发布于 2021-12-16 11:57:06
可以使用reduce将数组转换为对象,并将其转换回数组。
const array = Object.entries([
{ group: '1', tag: ['sins'] },
{ group: '1', tag: ['sun'] },
{ group: '2', tag: ['red'] },
{ group: '2', tag: ['blue'] },
{ group: '2', tag: ['black'] },
].reduce((acc, { group, tag }) => ({ ...acc, [group]: acc[group] ? acc[group].concat(tag) : tag}), {})).map(([group, tag]) => ({ group, tag }));
console.log(array);
发布于 2021-12-16 11:51:17
请读取javascript数组的文档. https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array
你有几种方法来解决你的问题。
发布于 2021-12-16 11:56:45
const array = [
{ group: '1', tag: ['sins'] },
{ group: '1', tag: ['sun'] },
{ group: '2', tag: ['red'] },
{ group: '2', tag: ['blue'] },
{ group: '2', tag: ['black'] },
];
// using reduce to create dictionary and taking group value as key:
let groupDicionry = array.reduce((dic, obj) => {
// create object if already not in dictionary
if(!dic[obj.group]) { dic[obj.group] = { group: obj.group, tag: [] }; };
dic[obj.group].tag.push(obj.tag[0]);
return dic
}, {});
let result = Object.values(groupDicionry);
console.log(result);
https://stackoverflow.com/questions/70378442
复制相似问题