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



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

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

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

最新更新