I have an array of objects like this:
const array = [
{
dates: [
{
date: "01",
test: "FO",
},
{
date: "07",
test: "AB",
},
],
login: "TESTE.TESTE",
},
{
dates: [
{
date: "02",
test: "AB",
},
{
date: "04",
test: "FO",
},
],
login: "TESTE.TESTE",
},
];
And I want it to be like this:
const array = [
{
dates: [
{
date: "01",
test: "FO",
},
{
date: "02",
test: "AB",
},
{
date: "04",
test: "FO",
},
{
date: "07",
test: "AB",
},
],
login: "TESTE.TESTE",
},
];
Basicaly I want to concat the objects with same 'login' property, and concat theirs 'dates' array and then fill it with the missing days, like: 01, 02, 03....31
As suggested in the comments, just a simple reduce with conditional push.
const array = [
{
dates: [{ date: "01", test: "FO" }, { date: "07", test: "AB" }],
login: "TESTE.TESTE"
},
{
dates: [{ date: "02", test: "AB" }, { date: "04", test: "FO" }],
login: "TESTE.TESTE"
}
];
const result = array.reduce((res, curr) => {
const found = res.find(el => el.login === curr.login);
if (found) {
found.dates.push(...curr.dates);
} else {
res.push(curr);
}
return res;
}, []);
console.log(result);