javascript - 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: []},
]
}
解决方案
由于其他类别需要有空数组,因此最好的方法是删除产品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))
})
推荐阅读
- ios - 在 WKWebView 上设置最小和最大缩放或完全禁用它
- php - 将php字符串转换为数组数组
- sql - 当我将值插入表中时,违反了 PK
- google-cloud-platform - 添加另一个节点后 Cloud Composer 抛出 InvalidToken
- matlab - 如何从 3D 点云的边界生成横截面?
- google-app-engine - 0 个实例的 Google App Engine 柔性环境
- python - 试图在嵌套字典中查找唯一值的总和。(见例子!)
- r - 对数据进行分组并计算频率并在 R 中基于它们创建新列
- nginx - nginx 重定向到相同的 url
- java - 图形将矩形溢出填充到新的矩形中?