Incorporating an element into a nested array

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!

Answer №1

To solve this issue, you can iterate through the items and include the missing field if it's not already there:

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);

It's recommended to use Math.ceil() rather than Math.floor() since you specified a value between 1 and 100.

Answer №2

If you're looking to transform an array in JavaScript, consider using the map() method.

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

const result = items.map(item => (item.popularity ? item : { ...item, popularity: Math.floor(Math.random() * 100) }));

console.log(result);

Answer №3

Your code if ([6 == 'undefined']) - It's not a syntax error, but rather a complete logical error. It equates to if ([false]) because the two constants are not the same, ultimately resulting in if (true) since it's a non-empty array.

There are more efficient ways to achieve this, with the best approach being to use the Array.map() function:

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

const result = items.map(item => (item.popularity ? item : { ...item,
  popularity: Math.floor(Math.random() * 100)
}));

console.log(result);

Answer №4

Implementing map alongside the nullish coalescing operator (??) can be powerful

const products = [
  { 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 },
];

const updateProducts = (arr) =>
  arr.map(({ popularity, ...item }) => ({
    popularity: popularity ?? Math.floor(Math.random() * 100) + 1,
    ...item,
  }));

console.log(updateProducts(products));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality to deselect multiple options in a select box is not functioning properly

There seems to be an issue with removing the selected attribute from the selected values in a jQuery multiselect box. The console is not showing any errors. You can view a working example here The problem lies in this code snippet: $("#mltyslct option ...

Pressing element against another element

I have a somewhat unconventional request - I want to trigger a click event with an HTML element while hovering over another element. Let's imagine we have a .cursor element hovering over an anchor text. In this scenario, clicking on the .cursor shoul ...

Steps for iterating through an array within an object

I currently have a JavaScript object with an array included: { id: 1, title: "Looping through arrays", tags: ["array", "forEach", "map"] } When trying to loop through the object, I am using the following ...

Struggling with adding headers in React application

When I try to include an h1 heading, either the heading doesn't show up if I comment out the buttons, or if I comment out the heading, then the buttons don't display. But when both are included, nothing is displayed. Any suggestions on how to fix ...

What is the best method for designing a filtering menu with a "Narrow By" option?

Looking to create a sidebar menu similar to the functionality on mcmaster.com. This specific feature allows users to efficiently filter products and toggle through different options dynamically. Upon selecting the "metric" option, the entire page adjusts t ...

In JavaScript, a nameless function is being returned within another nameless function

Can the getNameFun function just return this.name instead of an anonymous function? Is there a reason for this structure? Code Segment 1: var name = "The Window";   var object = {     name : "My Object",     getNameFunc : function(){ ...

Extracting web search result URLs using Puppeteer

I'm currently facing an issue with the code I've written for web scraping Google. Despite passing in a specific request, it is not returning the list of links as expected. I am unsure about what might be causing this problem. Could someone kindly ...

Convert an AJAX JSON object into values for multiple text boxes

When making an ajax call, I receive the following JSON input: var json = { "id_u":"1", "nombre_usuario":"JESUS", "apellido_paterno_usuario":"DIAZ", } I have text inputs that correspond to each key in the JSON object: <input type="text" name="id ...

Implement a jQuery loading animation triggered by scrolling down the page

Can anyone offer guidance on how to trigger an animation as you scroll down a webpage? I've come across this feature while browsing through this website: I would love to include code examples, but I'm unsure of where to start with implementing t ...

What is the best way to retrieve a specific object from a JSON file using a Get request in a Node.js application?

My focus is on optimizing an API, which is why I'm working with only the data that's essential for my analysis. I've set up a route to extract specific objects, but I'm only interested in four of them: account_manager, fronter, closer, ...

Is there a way to display various data with an onClick event without overwriting the existing render?

In the process of developing a text-based RPG using React/Context API/UseReducer, I wanted to hone my skills with useState in order to showcase objects from an onclick event. So far, I've succeeded in displaying an object from an array based on button ...

Issue with Angular ngFor not updating radio button value when ngModel is set

Hello, I am fairly new to working with Angular and could really use some assistance with a problem I've run into. Essentially, I am receiving an array of objects from an API like this: [{name: "abc", score: 2},{name: ""def, score: ...

What methods can I use to ensure that a user's credentials are not shown in the URL?

My NextJS application sometimes behaves unexpectedly. Whenever I have a slow connection and the initial load time of the site is longer than usual, after trying to log in to the application, the credentials I entered are displayed in the URL. This happens ...

Assign the value of one variable to another variable using the same keys

I'm facing a scenario where I have two arrays named array1 and array2. My goal is to transfer the values from array2 into array1 for the properties that exist in array1, while keeping the default values for any properties that are not present. One ap ...

What is the process of setting up an array and populating it with characters from a buffer

In my code, there is a method that looks like this: int create_nodes(Source* source, int maxTokens) { int nodeCount = 0; Token* p_Tstart = source->tknBuffer; Token* p_Tcurrent = source->tknBuffer; while ((p_Tcurrent - p_Tstart) < ...

An introduction to integrating Paged.js with Vue.js3

index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> < ...

Having difficulties executing a JavaScript file in the command prompt

I'm having trouble running a JavaScript file in the command prompt. Can anyone assist me with this issue? D:\>Node Welcome to Node.js v12.14.1. Type ".help" for more information. > 001.js undefined > Node 001.js Thrown: Node 001.js ...

How can I access specific values from a table generated with a PHP array using jQuery?

Currently, I am working on a page where users can upload documents. Once uploaded, these docs are stored in a folder and their location is updated in a table for reference. Now, when I navigate to an edit page, I use PHP to query the database and display t ...

C programming language's dynamic character matrix with three dimensions

I am looking to create a three-dimensional array of strings, with each row containing two strings. This is how I have been able to declare it: char *szArray[][2] = { {"string1", "string2"}, {"string3", "string4"}, {"string5", "string6"}, ...

Managing dependencies with Yarn or npm

While experimenting with remix and mui v5, I encountered some issues. When using npm and running npm run dev, I received the following error: Error: Directory import '.../playground/remix-mui-dev/node_modules/@mui/material/styles' is not supporte ...