Ad

Adding Object To Multidimensional Array

- 1 answer

I currently have this 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},             

];

and want to add a random popularity score between 1 and 100 for the items that currently have to entry.

My current code:

for (var n = 0; n < 3; ++n) {           
if ([6 == 'undefined']) {  
var randomNum = Math.floor(Math.random() * 100);  
    items.push(('popularity:'), (randomNum));   

gives me the array:

[

{
  description: "12inch",
  name: "tablet",
  popularity: 99,
  price: 700
}, 

{
  description: "8inch",
  name: "phone",
  price: 900
}, 

{
  description: "32inch",
  name: "computer",
  popularity: 50,
  price: 3000
}, 

{
  dimensions: "17inch",
  name: "laptop",
  price: 1500
}, "popularity:", 51, "popularity:", 38, "popularity:", 92]

when i console.log it,

So I am wondering how it is that I can loop through both the dimensions of the array, the rows and columns so the array would appear as:

{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}, 

Thanks!

Ad

Answer

You can just loop over the items, and add the missing field if it's not present:

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 },
];

items.forEach(i => i.popularity = i.popularity || Math.ceil(Math.random() * 100));

console.log(items);

Since you're stating that you want a value between 1 and 100, you might want to use Math.ceil() instead of Math.floor().

Ad
source: stackoverflow.com
Ad