简体   繁体   中英

How to filter the entire array based on user input using filter in JavaScript ?

I am trying to use a filter in javascript to search on an array. Following is my array:-

 "customerStatusInfoList": [
            {
                "customerId": 1110000012,
                "caseStatus": "pending",
                "customerName": "Robert",
                "dateOfRequest": "2018-12-15 00:00:00.0"
            },
            {
                "customerId": 1110000004,
                "auditorName": "DcbAdmin",
                "caseStatus": "pending",
                "customerName": "Sam",
                "dateOfRequest": "2018-12-14 12:40:04.0"
            }
        ]

And I am using the following function to filter the array:-

  filterTable = event => {
    console.log("event.target.value", event.target.value);
    console.log("rows", this.state.rows);

    if (event.target.value !== "") {
      let newRow = this.state.rows.filter(items => {
        console.log("item.name", items.customerName);
        if (items.customerName!== null)
          return items.customerName
            .toLowerCase()
            .includes(event.target.value.toLowerCase());
      });

      this.setState({ rows: newRow, query: event.target.value });
    } else {
      console.log("Query string is empty ", event.target.value);
      let newRow = this.state.custList;
      console.log("new row :", newRow);
      this.setState({ query: event.target.value, rows: newRow });
    }
  };

I am able to filter on the customerName but when I try to filter using customerId or any other parameter I get customerId.includes is not a function. But it works on customerName. How can I filter on the entire table using JavaScript filter? Any help or suggestion is appreciated. Thank you.

I added a test for type in here.

  filterTable = event => {
    console.log("event.target.value", event.target.value);
    console.log("rows", this.state.rows);

    if (event.target.value) {
      let newRow = this.state.rows.filter(items => {
        console.log("item.name", items.customerName);
        if(typeof event.target.value == 'string') {
        if (items.customerName!== null)
              return items.customerName
                          .toLowerCase()
                          .includes(event.target.value.toLowerCase()); 
            } else if(typeof event.target.value === 'number' {
              return items.cusomterId === event.target.value);
            }         
      });

      this.setState({ rows: newRow, query: event.target.value });
    } else {
      console.log("Query string is empty ", event.target.value);
      let newRow = this.state.custList;
      console.log("new row :", newRow);
      this.setState({ query: event.target.value, rows: newRow });
    }
  };

customerId is an integer - you need to cast to string, eg:

return `${items.customerId}`
  .toLowerCase()
  .includes(event.target.value.toLowerCase());

btw, items is a confusing name for the variable - it's a single item

also, you can simplify things a bit by decomposing the item, ie:

let newRow = this.state.rows.filter(({customerId, customerName}) => 
  `${customerName || ''}`
    .toLowerCase()
    .includes(event.target.value.toLowerCase())
);

to include any row that matches customerId , customerName , or auditorName :

let newRow = this.state.rows.filter(({customerId, customerName, auditorName}) => 
  [customerId, customerName, auditorName].some(field => 
    `${field || ''}`
      .toLowerCase()
      .includes(event.target.value.toLowerCase()))
);

Hi I have added some pure javascipt logic which you can embed in your react component as per your need .

Here you can replace the targetName and targetValue comming from the state values of the component.

Having switch case will allow you to add different logic for different kind of fields.

const data = {
    "customerStatusInfoList": [
        {
            "customerId": 1110000012,
            "caseStatus": "pending",
            "customerName": "Robert",
            "dateOfRequest": "2018-12-15 00:00:00.0"
        },
        {
            "customerId": 1110000004,
            "auditorName": "DcbAdmin",
            "caseStatus": "pending",
            "customerName": "Sam",
            "dateOfRequest": "2018-12-14 12:40:04.0"
        }
    ]
}

const targetName = 'customerId';
const targetValue = 1110000004;

callback = (value, index, array) => {

    switch (targetName) {
        case "customerName":
            return value.customerName === targetValue;
        case "customerId":
            return value.customerId === targetValue;
        default:
            return value.customerName === targetValue;
    }
}

let result = data.customerStatusInfoList.filter(callback, this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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