I have two arrays
Array1
{"Colour":"RASPBERRY","Size":"11"}
and a list of products
Array2
[
{
"ProductID": 33043,
"Key": "Colour",
"Value": "RASPBERRY"
},
{
"ProductID": 33043,
"Key": "Size",
"Value": "4"
},
{
"ProductID": 33044,
"Key": "Colour",
"Value": "RASPBERRY"
},
{
"ProductID": 33044,
"Key": "Size",
"Value": "5"
},
{
"ProductID": 33045,
"Key": "Colour",
"Value": "RASPBERRY"
},
{
"ProductID": 33045,
"Key": "Size",
"Value": "6"
},
{
"ProductID": 33046,
"Key": "Colour",
"Value": "RASPBERRY"
},
{
"ProductID": 33046,
"Key": "Size",
"Value": "7"
},
{
"ProductID": 33047,
"Key": "Colour",
"Value": "RASPBERRY"
},
{
"ProductID": 33047,
"Key": "Size",
"Value": "8"
}
]
I have both those arrays, I need to fetch ProductID from Array2 Using the data from Array 1, the list can be thousands long, want to avoid heavy work
Below is my attempt:
// Step 1: Group entries in array2 by ProductID
var productDict = {};
$.each(array2, function(index, entry) {
var productID = entry.ProductID;
var key = entry.Key;
var value = entry.Value;
if (!productDict[productID]) {
productDict[productID] = {};
}
productDict[productID][key] = value;
});
// Step 2: Check each ProductID group against the criteria in array1
var matchingProductIDs = [];
$.each(productDict, function(productID, attributes) {
var match = true;
$.each(array1, function(key, value) {
if (attributes[key] !== value) {
match = false;
return false; // Break out of the loop
}
});
if (match) {
matchingProductIDs.push(productID);
}
});
// Output the result
console.log("Matching Product IDs:", matchingProductIDs);
the above code works, but it seems heavy and would like a better solution, if anyone can help.