Refreshing a nested object by modifying its array elements in JavaScript

Hello, I am looking for assistance in updating the userSettings variable. Specifically, when a product is removed from the products array, I need to update the sortedProducts array within the userSettings.categories array. I have attempted to accomplish this using nested for loops, but I am interested in optimizing performance by utilizing functional array methods. Below is my current attempt. Thank you in advance for your help!

let products = [
        {id: 1, name: 'Brasilian', category: 'cofee'},
        {id: 2, name: 'Colombian', category: 'cofee'},
        {id: 3, name: 'Apple', category: 'fruit'},
        {id: 4, name: 'Strawberry', category: 'fruit'},
        {id: 5, name: 'Banana', category: 'fruit'},
        {id: 6, name: 'Pepper', category: 'spices'},
        {id: 7, name: 'Salt', category: 'spices'}
    ]
    
let userSettings = {
    categories: [
        {name: 'fruit', sortedProducts: [5, 3, 4]},
        {name: 'spices', sortedProducts: []},
        {name: 'cofee', sortedProducts: []},
    ]
}

// lets remove the strawberry product
products.splice(3, 1);
console.log(products);


// i need to update userSettings
const updateUserSettings = (() => {

    for(let i = 0; i < userSettings.categories.length; i++){

        if(userSettings.categories[i].sortedProducts.length){
            console.log(userSettings.categories[i].sortedProducts);

            for(let j = 0; j < products.length; j++){
                if(products[j].category == userSettings.categories[i] && !userSettings.categories[i].sortedProducts.includes(products[j].id)){
                    console.log('no includes')
                }
            }
      
        }
    }

})();






expectedOutput = {
    categories: [
        {name: 'fruit', sortedProducts: [5, 3]},
        {name: 'spices', sortedProducts: []},
        {name: 'cofee', sortedProducts: []},
    ]
}

Answer №1

If you want to ensure that all categories have empty arrays, the most effective approach is to eliminate any current sortedProducts in userSettings that are no longer present in the products list.

userSettings.categories.forEach(category => {
    // Obtain the product ids for the category
    let filteredProductIds = products.filter(product => product.category === category.name)
        .map(product => product.id)
    // Remove any id from sortedProducts that is no longer found in the products list
    category.sortedProducts = category.sortedProducts.filter(sortedProduct => filteredProductIds.includes(sortedProduct))
})

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

Navigating the ropes of push-pull functionality in Bootstrap 5

How can I utilize push and pull in Bootstrap version 5.0.0-beta2? In Bootstrap 3, my code looks like this: <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet" /> <div class="row"> <d ...

Handy Node.js package for building a JSON API in a Ruby on Rails application

In the process of creating my Titanium Mobile app, I encountered a connection with a Rails JSON API. I found myself needing to create model objects for Rails model objects, which became quite tedious due to pagination and other factors. I am on the looko ...

Error with decodeURIComponent function in Internet Explorer 8

My widget, loaded as an iframe, requires data about the hosting page. I have UTF-8 strings extracted from a page with Russian text. The page itself has proper HTML5 doctype and meta charset. This is how my code operates: params = "x1=" + encodeURICompone ...

Consistent Failure: jQuery File Upload consistently aborts with the error message 'File upload aborted'

I'm currently utilizing the Blueimp File Upload Plugin to facilitate file uploads to a remote server. The HTML code snippet for the file upload input is as follows: <input id="fileupload" type="file" name="files[]" data-url="http://my-server-ip/u ...

Issue encountered when integrating JavaScript into Django view form update

I have successfully implemented a Django view to add an invoice to my application, complete with added JavaScript functionality that is functioning properly. <p> <label for="id_total_without_vat">Price</label> <input ...

The back-to-top button guides users back to their last visited page

I'm excited to explore AngularJS and I want to add two "return to top" buttons on different pages. Here's what I have so far: Page 1: <h1 id = "top"> .......... <a href="#top" target = "_self">Return to Top</a> Page ...

Picture is not showing up on my MVC software

Within a table containing multiple other tds, I am having an image tag. <table class="MyClass"> <tr> <td> @Html.LabelFor(m => m.ShopName) </td> <td> @Html.TextBoxFor(mode ...

Limit certain website functions exclusively for members

I am currently working on a website that offers a set of basic features for all users, along with some exclusive features reserved for members. For example, all visitors can read posts, but only members have the ability to add tags, share posts, and more. ...

Retrieve the duplicated items from an array by comparing two specific properties in JavaScript

I need assistance in identifying and retrieving duplicate objects within an array that share similarities in 2 specific properties. Consider the object structure below: let arry = [ {Level: "A-1", Status: "approved"}, {Level: &q ...

Using SABA to access web services

I am looking to customize a SABA page by adding an HTML button that, when pressed, will call a web service to retrieve an answer based on input parameters and take appropriate action. The web service accepts a JSON variable as input, structured like this: ...

Ways to adjust the vAxis and hAxis labels to display as whole numbers

Below is the code provided: var rawdata='".$performances."'; var mydata=jQuery.parseJSON(rawdata); if(mydata){ var realData=[]; realData=[ ['Activities', &a ...

create new Exception( "Invalid syntax, expression not recognized: " msg );

Can someone assist me in identifying the issue at hand? Error: There seems to be a syntax error, and the expression #save_property_#{result.id} is unrecognized. throw new Error( "Syntax error, unrecognized expression: " msg ); Here is the c ...

Enhancing button functionality using jQuery and JavaScript for toggling behavior

I am facing a challenge with this code. The goal is to have a single script that can handle multiple audio elements on the page and toggle between PLAY and PAUSE buttons by adding or removing classes. Can anyone suggest any changes or additions that coul ...

Having trouble with accessing input field in a modal that was generated by TinyMCE React within a Next.JS environment

In my current project, I am utilizing Next.JS and looking to incorporate the TinyMCE editor onto my webpage. Here is the code snippet I have implemented: <TinyMceEditor selector='textarea' initialValue={ props.value } apiKey=<AP ...

Enhancing Nested Objects using Mongoose

When attempting to update nested objects using Mongoose, the request I receive appears like this: { 'example[apple]': 'false', 'example[pear]': 'false', 'example[banana]': 'false', 'example[ ...

What is the process for creating a method within a Vue directive?

How can I define a local method inside my directive and utilize it within the bind and componentUpdated functions? Below is the code snippet in question: export const OutsideClick = { bind (el, binding, vnode) { console.log(new Vue()); // call ...

Inquiry about Tree Traversal in Javascript using Jquery

Consider the following scenario: <ul> <li>Item 1</li> <li>Item 2 <ul> <li>Sub Item</li> </ul> </li> <li>Item 3</li> </ul> This list is dynamically generated by another piec ...

Highchart tip: How to create a scrollable chart with only one series and update the x-axis variable through drilldown

Before I pose my question, here is a link to my jsfiddle demo: http://jsfiddle.net/woon123/9155d4z6/1/ $(document).ready(function () { $('#deal_venue_chart').highcharts({ chart: { type: 'column' ...

Separate the string by using a comma to create new lines

I'm trying to figure out how to split a string by commas and create new lines. I tried using the split and join functions, but it's only removing the commas without actually creating new lines. string='Lorem Ipsum,Lorem Ipsum,Lorem Ipsum&ap ...

What could be causing this server side rendering error even though I clearly instructed the component to render on the client side?

I'm encountering an issue with a component that should be rendered on the client side, but I'm getting an error message in the terminal stating that it cannot read localStorage because it is undefined. This error occurs because the application is ...