I have created Shopping Cart the product name, image, price, and attributes are created in separate components. I'm getting an issue where I wanted to get only the specific product variation's attribute, but I got all product variation attributes as below image
Above show the product and its details, but the product attributes must show only its specific variation attributes but it shows all its variation attributes. below is the code and the MongoDB database structure of the product.
I don't know where I go wrong, plz help me. thank you in advance.
You can use the array filter method if you want to get a subset of the attributes. For example:
const res = {
data: {
VariationList: {
Attribute: {
Weight: 1,
Length: 2,
Width: 3,
Hook: 4
}
}
}
};
function getProductAttributes(data, filterList = []) {
const entries = Object.entries(data.VariationList.Attribute);
if (!filterList.length) return entries;
return entries.filter((attr) => filterList.includes(attr[0]));
}
let output = getProductAttributes(res.data);
console.log(output); // [ [ 'Weight', 1 ], [ 'Length', 2 ], [ 'Width', 3 ], [ 'Hook', 4 ] ]
output = getProductAttributes(res.data, ['Weight', 'Length']);
console.log(output); // [ [ 'Weight', 1 ], [ 'Length', 2 ] ]