javaScript过滤嵌套对象和数组 [英] javaScript filter nested objects and arrays

查看:68
本文介绍了javaScript过滤嵌套对象和数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用例是这样的.

  1. 我有一个包含对象的数组.
  2. 每个对象都有一个名为 menu
  3. 的数组
  4. 再次反对菜单数组.
  5. 每个对象都有一个数组 dish_has_categories
  6. dish_has_categories 数组中,如果存在CategoryId等于 8 的对象,我想过滤掉该根对象.
  1. I have an array that has an object.
  2. That each object has an array called menu
  3. Again that menu array has objected.
  4. That each object has an array dish_has_categories
  5. In dish_has_categories array, if there is an object with CategoryId is equal to 8 I want to filter out that root object.

我的原始数据对象

const data = [{
        menuName: "Hot dogs",
        menu: [
            {
            dishId: '1',
            dish_has_categories: [{
                CategoryId: '8'
            }]
        },
         {
            dishId: '2',
            dish_has_categories: [{
                CategoryId: '9'
            }]
        }]
    },
    {
        menuName: "Burgers",
        menu: [{
            dishId: '3',
            dish_has_categories: [{
                CategoryId: '6'
            }]
        }, {
            dishId: '4',
            dish_has_categories: [{
                CategoryId: '4'
            }]
        }]
    },
    {
        name: "Drinks",
        menu: []
    }
]

我的预期结果是

[{
        menuName: "Hot dogs",
        menu: [
            {
            dishId: '1',
            dish_has_categories: [{
                CategoryId: '8'
            }]
        },
         {
            dishId: '2',
            dish_has_categories: [{
                CategoryId: '9'
            }]
        }]
    }]
    

我到目前为止所做的是

const data2 = data.filter(element => {
    return element.menu.length > 0
})

我不知道如何在嵌套对象和数组内部进行深度过滤.希望我的问题对大家都清楚.

I have no idea how to deep filter inside nested objects and arrays. Hope my question is clear to you all.

推荐答案

您可以使用

You can use filter and some

在此处嵌套一些用于检查 dish_has_categories 中的任何一个是否具有等于'8' CategoryId ,如果它是 true,然后在最终输出中包含该菜单,否则我们不会

Here nested some is used to check whether any of dish_has_categories has CategoryId equal to '8', if it is true then we include that menu in final output else we don't

const data =[{ menuName: "Hot dogs", menu: [ { dishId: '1', dish_has_categories: [{ CategoryId: '8' }] }, { dishId: '2', dish_has_categories: [{ CategoryId: '9' }] }] }, { menuName: "Burgers", menu: [{ dishId: '3', dish_has_categories: [{ CategoryId: '6' }] }, { dishId: '4', dish_has_categories: [{ CategoryId: '4' }] }] }, { name: "Drinks", menu: [] } ]

let op = data.filter(val => {
  let menu = val.menu.some(({dish_has_categories}) => dish_has_categories.some(({CategoryId}) => CategoryId === '8'))
  return menu
})

console.log('filtered values -->\n',op)

let names = op.map(({menuName})=> menuName)

console.log('Names --> \n', names)

这篇关于javaScript过滤嵌套对象和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆