My working solution:
let final = [];
let sample = [
{ tribe_id: 1, tribe_name: "Tribe A", squad_id: 1, squad_name: "Squad A" },
{ tribe_id: 1, tribe_name: "Tribe A", squad_id: 2, squad_name: "Squad B" },
{ tribe_id: 2, tribe_name: "Tribe B", squad_id: 3, squad_name: "Squad C" }
];
console.log(sample);
const uniqueTribes = sample.reduce((acc, current) => {
const x = acc.find(item => item.tribe_id === current.tribe_id);
if (!x) {
// return acc.concat([current]);
return acc.concat([{ "tribe_id": current.tribe_id, "tribe_name": current.tribe_name, "squads": [] }]);
}
return acc;
}, []);
// console.log(uniqueTribes);
for (let i = 0; i < uniqueTribes.length; i++) {
let uniqueTribeName = uniqueTribes[i].tribe_name;
let uniqueTribeId = uniqueTribes[i].tribe_id;
for (let x = 0; x < sample.length; x++) {
let squadName = sample[x].squad_name;
let squadId = sample[x].squad_id;
if (uniqueTribeId == sample[x].tribe_id) {
// uniqueTribes[i].squads.push({ squad_id: sample[x].squad_id, squad_name: sample[x].squad_name });
uniqueTribes[i].squads.push({ squad_id: squadId, squad_name: squadName });
}
}
// let uniqueTribeId = sample[i].squad_name;
}
console.log(uniqueTribes);
let tribe = [];
// console.log(tribe);
let desiredFormat = [
{
tribe_id: 1, tribe_name: "Tribe A", squads: [
{squad_id: 1, squad_name: "Squad A"},
{squad_id: 2, squad_name: "Squad B"}
]
},
{
tribe_id: 2, tribe_name: "Tribe B", squads: [
{squad_id: 3, squad_name: "Squad C"}
]
}
];
solved Javascript array arrange parent and child as array?