简体   繁体   English

从对象数组中过滤数据包含对象数组

[英]Filter data from Array of Objects contains Array of Objects

Here I have attendance details and I Want to filter every data that contains employees id:1 .在这里,我有出勤详细信息,我想过滤包含员工id:1的每个数据。
for example: I have data like this:例如:我有这样的数据:

const attendance = [
        {
            date: 1,
            employees: [
                {
                    id: 1,
                    name: 'mahadev',
                    status: 'p'
                },
                {
                    id: 2,
                    name: 'roshan',
                    status: 'p'
                },

            ]
        },
        {
            date: 2,
            employees: [
                {
                    id: 1,
                    name: 'mahadev',
                    status: 'a'
                },
                {
                    id: 2,
                    name: 'roshan',
                    status: 'p'
                },

            ]
        },
    ];

And I want Output like this:我想要这样的 Output :

[
  {
    date:1,
    employees: [
      {
        id:1,
        name:'mahadev',
        status:'p'
      }       
    ]  
  },
  {
    date:2,
    employees: [
      {
        id:1,
        name:'mahadev',
        status:'a'
      }       
    ]  
  },
]

Try using map and filter .尝试使用mapfilter

 const attendance = [{ date: 1, employees: [ { id: 1, name: 'mahadev', status: 'p' }, { id: 2, name: 'roshan', status: 'p' } ] }, { date: 2, employees: [ { id: 1, name: 'mahadev', status: 'a' }, { id: 2, name: 'roshan', status: 'p' } ] }, ]; const filtered = id => attendance.map(a => { const employees = a.employees.filter(e => e.id === id); return {...a, employees }; }); console.log(filtered(1));

Using map() and filter()使用map()filter()

const filtered = id =>
  attendance.map(a => {
    const employees = a.employees.filter(emp => emp.id === id);
    return { date:a.date, employees };
  });
console.log(filtered(1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM