I have this simple array of two objects where I need to get the price of the products of 1 month.
The array can 2 or 3 items so I'm checking whether it is 2 or 3. Then I'm storing the objects in their own variable and calling the function getOneMonthPrice
with parameter value of those variables.
The function getOneMOnthPrice
loops over the products and checks if the months property as a value of 01 month
, and if it does then it returns the price.
But right now I'm only getting undefined, whereas if I use console.log inside the functions, I can see the values showing in the console.
What is going wrong here?
Please note that I have actually removed most of the codes from the actual project where I'm working on. This is just the shortest version. If you can please give me a solutoin based on this format.
Here's the snippet:
const arr = [{
"name": "Boom Boom Ltd.",
"products": [{
"price": "3.33",
"months": "24 months"
},
{
"price": "10.95",
"months": "01 month"
}
]
},
{
"name": "Bam Bam Ltd.",
"products": [{
"price": "5.93",
"months": "24 months"
},
{
"price": "12.95",
"months": "01 month"
}
]
}
];
function getOneMonthPrice(company) {
company.products.forEach(item => {
if (item.months === "01 month") {
return item.price;
}
});
};
if (arr.length === 2) {
const company1 = arr[0];
const company2 = arr[1];
console.log(getOneMonthPrice(company1));
}