Before
const array = [
{ group: '1', tag: ['sins'] },
{ group: '1', tag: ['sun'] },
{ group: '2', tag: ['red'] },
{ group: '2', tag: ['blue'] },
{ group: '2', tag: ['black'] },
];
After
const array = [
{ group: '1', tag: ['sins', 'sun'] },
{ group: '2', tag: ['red', 'blue', 'black'] },
];
I want to change it like the chord above. I want someone to create a cool chord.
CodePudding user response:
You can convert the array to an object using reduce
and convert it back to an array.
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);
CodePudding user response:
Please read the docs for the javascript array. https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array
you have several methods to solve your problem.
CodePudding user response:
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);