从内部有一个数组的数组中过滤数据

时间:2019-02-07 07:42:04

标签: javascript

在我的代码中,我有一个对象数组。该对象数组应该根据给定的输入值进行过滤。我有一个输入字段来过滤它。我在安慰时得到过滤后的值,但它不会覆盖现有值。  这是我的数据结构。我必须过滤名称。 我写的代码如下。

this.customerDetails = [
        {
          date:'13',
           contacts:[
             {name:"Ashish", time:"4:00 AM", guests:2},
             {name:"Kevin", time:"4:00 AM", guests:2},
             {name:"Veena", time:"4:00 AM", guests:2},
             {name:"Pruthvi", time:"4:00 AM", guests:2},
             {name:"Rahul", time:"4:00 AM", guests:2},
           ]
         },
         {
           date:'22',
            contacts:[
              {name:"Jixon", time:"4:00 AM", guests:2},
              {name:"Hari", time:"4:00 AM", guests:2},
              {name:"Keerthi", time:"4:00 AM", guests:2},
              {name:"Roma", time:"4:00 AM", guests:2},
              {name:"Franko", time:"4:00 AM", guests:2},
            ]
          }
      ]

getInputItems(e: any){
    const val = e.target.value;
    if (val && val.trim() != '') {
      this.customerDetails = this.customerDetails.map((item) => {
        const data=
        item.contacts.map((customerDetail)=>{
        return 
(!(customerDetail.name.toLowerCase().indexOf(val.toLowerCase())));
        })
        return {date: item.date, contacts: data}
      })
    }
  }

过滤后,我希望得到这样的结果,

this.customerDetails = [
        {
          date:'13',
           contacts:[
             {name:"Ashish", time:"4:00 AM", guests:2},
           ]
         },
      ]

谢谢。

1 个答案:

答案 0 :(得分:0)

您的代码中存在多个错误,您尝试多次返回,并且可以使用filter代替第二张地图:

const customerDetails = [
    {
        date: '13',
        contacts: [
            { name: 'Ashish', time: '4:00 AM', guests: 2 },
            { name: 'Kevin', time: '4:00 AM', guests: 2 },
            { name: 'Veena', time: '4:00 AM', guests: 2 },
            { name: 'Pruthvi', time: '4:00 AM', guests: 2 },
            { name: 'Rahul', time: '4:00 AM', guests: 2 },
        ],
    },
    {
        date: '22',
        contacts: [
            { name: 'Jixon', time: '4:00 AM', guests: 2 },
            { name: 'Hari', time: '4:00 AM', guests: 2 },
            { name: 'Keerthi', time: '4:00 AM', guests: 2 },
            { name: 'Roma', time: '4:00 AM', guests: 2 },
            { name: 'Franko', time: '4:00 AM', guests: 2 },
        ],
    },
];

const getInputItems = (val) => {
    if (val && val.trim() != '') {
        return customerDetails.map((item) => ({
          date: item.date,
          //filter out items that do not contain search value
          contacts:item.contacts.filter((customerDetail) => {
            return customerDetail.name.toLowerCase().includes(val.toLowerCase());
          })
        }))
        //filter out items that have no contacts
        .filter(
          (item)=>!!item.contacts.length
        )
    }
};

console.log(getInputItems('jix'));