同时过滤对象中的数组和另一个对象属性

分享于2022年07月17日 arrays filter javascript object 问答
【问题标题】:同时过滤对象中的数组和另一个对象属性(filter array in object and another object attribute at the same time)
【发布时间】:2022-07-12 22:20:06
【问题描述】:

这就是问题所在,我需要同时过滤“header”属性和内容,这是数据结构:

const testData = [
        {
            header: '公众号',
            content: [{ name: '系統公告'}],
        },
        {
            header: '我的群聊',
            content: [{ name: 'test01'}, { name: '下'}, { name: '公级用户'}],
        },
        {
            header: '上级用户',
            content: [{ username: 'root' }],
        },
        {
            header: '下级用户',
            content: [{ name: 'test0301'}, { name: '1234'},],
        },
    ];

如果我输入“下”之类的内容,数据应该如下所示:

const testData = [
        {
            header: '我的群聊',
            content: [{ name: '下'}],
        },
        {
            header: '下级用户',
            content: [{ name: 'test0301'}, { name: '1234'},],
        },
    ];

如果我输入“我”之类的内容,数据应该如下所示:

const testData = [
        {
            header: '我的群聊',
            content: [{ name: 'test01'}, { name: '下'}, { name: '公级用户'}],
        },
];

我只是花了十个小时思考这个,但我没有任何想法......

  • 在你的第一种情况 ,你想要像过滤器这样的内容(意味着不要添加其他名称接受 )。但在第二种情况下,您还需要其他名称。我想你不清楚你想要什么。

【解决方案1】:

你可以用 Array.reduce 做这样的事情

const filterData = (data, search) => data.reduce((res, item) => {
  if(item.header.includes(search)){
    return [
      ...res,
      item
    ]
  }
  const content = item.content.filter(({name}) => name && name.includes(search))
  
  if(content.length > 0){
    return [
     ...res,
     {...item, content}
    ]
  }
  
  
  return res

}, [])



const testData = [
        {
            header: '公众号',
            content: [{ name: '系統公告'}],
        },
        {
            header: '我的群聊',
            content: [{ name: 'test01'}, { name: '下'}, { name: '公级用户'}],
        },
        {
            header: '上级用户',
            content: [{ username: 'root' }],
        },
        {
            header: '下级用户',
            content: [{ name: 'test0301'}, { name: '1234'},],
        },
    ];
    
 console.log(filterData(testData, '下' ))
 console.log(filterData(testData, '我' ))