I have an array stored in a variable called 'items' with various products and their attributes. I am looking to randomly generate a popularity score between 1 and 100 for the items that currently do not have one.
This is my current array:
const items = [
{name: "tablet", description: "12inch", price: 700, popularity: 99},
{name: "phone", description: "8inch", price: 900},
{name: "computer", description: "32inch", price: 3000, popularity: 50},
{name: "laptop", dimensions: "17inch", price: 1500},
];
Here is the code snippet I am using:
for (var n = 0; n < 3; ++n) {
if (typeof items[n].popularity === 'undefined') {
var randomNum = Math.floor(Math.random() * 100);
items[n].popularity = randomNum;
}
}
When I console.log the array, I get the desired result:
{name: "tablet", description: "12inch", price: 700, popularity: 99},
{name: "phone", description: "8inch", price: 900, popularity: 51},
{name: "computer", description: "32inch", price: 3000, popularity: 50},
{name: "laptop", dimensions: "17inch", price: 1500, popularity: 32},
Any suggestions on how I can improve this code are welcome. Thank you!