代码之家  ›  专栏  ›  技术社区  ›  sonEtLumiere

JS使用数组更改更新嵌套对象

  •  0
  • sonEtLumiere  · 技术社区  · 3 年前

    嗨,我需要一些帮助来更新userSettings变量,例如,如果我删除了products数组的product,我需要更新userSettings.categories数组的sortedProducts数组,我正在尝试嵌套for循环,但是我想用函数数组方法来提高性能。这就是我一直在尝试的,提前感谢社区。

    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: []},
        ]
    }
    1 回复  |  直到 3 年前
        1
  •  1
  •   wxker    3 年前

    因为其他类别需要有空数组,所以最好的方法是删除任何现有的数组 sortedProducts 在里面 userSettings 不再存在于产品中。

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