I have three objects (productData, stockData, locationData). productData have two data productId, and productName. stockData have productId, locationId and stock. I wanna to merge it all to a new array. For example, I have three object like snippet code bellow then merge it:
const productData = [
{productId: 1000,productName: 'Product 1000'},
{productId: 1001,productName: 'Product 1001'}
];
const stockData = [
{productId: 1000,locationId: 1,stock: 21},
{productId: 1000,locationId: 2,stock: 8},
{productId: 1001,locationId: 1,stock: 4},
{productId: 1001,locationId: 2,stock: 10}
];
const locationData = [
{locationId: 1,locationName: 'Location 1'},
{locationId: 2,locationName: 'Location 2'}
];
I wanna to merge that object tobe a new array with result like:
const result = [
{
productName: 'Product 1000',
stock: {
total: 29,
detail: [
{
locationName: 'Location 1',
stock: 21
},
{
locationName: 'Location 2',
stock: 8
}
]
}
},
{
productName: 'Product 1001',
stock: {
total: 14,
detail: [
{
locationName: 'Location 1',
stock: 4
},
{
locationName: 'Location 2',
stock: 10
}
]
}
}
];
i have no idea, so far i do like this:
function mergeArrayObjects(arr1,arr2,arr3){
let mulai = 0;
let stok = 0;
let stok2 = 0;
let mulaiStok = 0;
let detail = [];
let merge = [];
while(mulai < arr1.length){
while(mulaiStok < arr2.length){
if(arr1[0].productId === arr2[mulaiStok].productId){
stok = stok + arr2[mulaiStok].stock
}
if(arr1[1].productId === arr2[mulaiStok].productId){
stok2 = stok2 + arr2[mulaiStok].stock
}
mulaiStok++
}
merge.push({
productName: arr1[mulai].productName,
stock: {
total:stok2,
detail:detail}
})
mulai++
}
return merge;
}
console.log(mergeArrayObjects(productData, stockData, locationData))