Is it possible to restructure parent data based on the child array data and its length? Should I stick with an array structure or consider changing the object array from the backend?
No IDs are present in the child arrays.
This is what has been accomplished:
this.arrays = [
{
id: '1',
idbid: '0000000001618',
name: 'ebi',
rate: '400',
bid: [
{
bid: 10000,
date: '2022/12/12',
value: 5000,
},
{
bid: 10000,
date: '2022/12/14',
value: 8100,
},
{
bid: 15000,
date: '2022/12/15',
value: 8100,
},
],
},
{
id: '2',
idbid: '0000000001618',
name: 'bio',
rate: '100',
bid: [
{
bid: 8000,
date: '2022/12/13',
value: 8000,
},
],
},
];
// Merge all item bids in the child array
let allVal: any = [];
allVal = allVal.concat(this.arrays.map((data) => data.bid).flat());
console.log(allVal);
// Get unique bids
var uniqueData = [];
allVal.forEach((item) => {
let count = uniqueData.filter((x) => x.value == item.value).length;
if (count == 0) {
uniqueData.push(item);
}
});
console.log(uniqueData);
// Find and merge into the parent array
const newArrays = uniqueData.map((obj) => {
return this.arrays.find((data) =>
data.bid.some((val) => val.value == obj.value)
);
});
console.log(newArrays);
// Restructure custom arrays of parents
const remapArrays = newArrays.map((obj, index) => {
return {
id: index + 1,
idbid: obj.idbid,
name: obj.name,
rate: obj.rate,
bid: obj.bid[index]?.bid,
date: obj.bid[index]?.date,
value: obj.bid[index]?.value,
};
});
console.log(remapArrays);
The result so far looks like this:
[
{
id: '1',
idbid: '0000000001618',
name: 'ebi',
rate: '400',
bid: 10000,
date: '2022/12/12',
value: 5000,
},
{
id: '2',
idbid: '0000000001618',
name: 'bio',
rate: '100',
bid: 10000,
date: '2022/12/13',
value: 8100,
},
{
id: '3',
idbid: '0000000001618',
name: 'ebi',
rate: '400',
bid: undefined,
date: undefined,
value: undefined,
},
];
The expected output should be:
// Final expected output
this.customArrays = [
{
id: '1',
idbid: '0000000001618',
name: 'ebi',
rate: '400',
bid: 10000,
date: '2022/12/12',
value: 5000,
},
{
id: '2',
idbid: '0000000001618',
name: 'bio',
rate: '100',
bid: 8000,
date: '2022/12/13',
value: 8000,
},
{
id: '3',
idbid: '0000000001618',
name: 'ebi',
rate: '400',
bid: 15000,
date: '2022/12/15',
value: 8100,
},
];
To test the code, visit Stackblitz