Can you help on how to combine data in two different arrays with different structures?
I take data via API, the first request:
[
{
"category_id": "12345",
"category_name": "itemgroup 1",
"category_is_hidden": "0",
"product_id": "9999999",
"product_name": "item 1",
"product_sku": "0002344",
"product_brand": null,
"product_vendor_code": "art 123",
"is_productset": "0",
"productset_items": null,
"is_service": "0",
"is_serial": "0",
"variations": {
"id": "1122334455",
"name": "red",
"measurement_unit": "unit_piece",
"quantity_minimal_piece": "1.000",
"sku": null,
"vendor_code": "",
"retail_price": "2550.00",
"wholesale_price": "2550.00",
"discount_type": "percent",
"discount": "0.00",
"barcodes": ["2000471000002", "2000481000009"]
}
}
]
second request:
[
{
"9999999": {
"company_id": 63,
"branch_id": 69,
"variation_id": 954629,
"supplier_id": 0,
"quantity": 1
}
}
]
I need to match the data by product_id and get the output in the format:
Product Name, Quantity
At the moment I only came up with:
async function getstockandproductinfo() {
try {
const stockinforesponse = await axios.get(`${BASE_URL}/stock?branch_id=0`, {
headers: {'API-KEY': API_KEY}
});
const productinforesponse = await axios.get (`${BASE_URL}/products`, {
headers: {'API-KEY': API_KEY}
});
const productdata = productinforesponse.data;
const stocksdata = stockinforesponse.data;
const meld = [].concat(productdata, stocksdata);
meld.forEach(item => {
if (typeof item === 'object' && item !== null) {
for (const product_id in item) {
if (item[product_id] && item[product_id].hasOwnProperty('quantity')) {
const quantity = item[product_id].quantity;
console.log(`Product ID: ${product_id}, Quantity: ${quantity}`);
}
}
}
});
} catch (error) {
console.error('Error', error);
}
}
getstockandproductinfo();
when I try to get the product name I get undefined
I will be glad for any help, as I am a complete noob)
4
Answers
Following is one way to do it:
this will do
You can loop the second array, find the key of each element, search for it in the first array via filter() and if found, copy the values at the appropriate keys via a loop:
If I understood correctly, you want to combine datasets that relate to the same product. Since I do not know what you want to do with the result later, here are two solutions that result in different data structures, each better suited for different uses after the combination.
The following combines into an
Array
:This gives an
Array
of related products combined which will make it easy to loop over it. If you need a specific product, you have to look for it by employing.filter/.find
.You could instead combine into an
Object
(or aMap
) instead of anArray
to make lookups faster if you only want to get (a) specific product(s) later:This would enable you to look for products by the value of their
product_id
: