首页 > 解决方案 > JS 使用数组更改更新嵌套对象

问题描述

嗨,我需要一些帮助来更新 userSettings 变量,例如,如果我删除 products 数组的产品,我需要更新 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: []},
    ]
}

标签: javascript

解决方案


由于其他类别需要有空数组,因此最好的方法是删除产品sortedProductsuserSettings不再存在的任何现有内容。

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

推荐阅读