简体   繁体   中英

How to return filtered array of object using the objects' keys

I want to write a function that takes two arguments (an array of objects and a search string). The function should return an array having filtered each of the object array by its respective keys.

My sample array and search string looks like this

const myArray = [{
  createdAt: 1579147513645,
  updatedAt: 1579147513645,
  id: 3,
  course: "Test",
  techStack: "Test ",
  …
} {
  createdAt: 1581047008746,
  updatedAt: 1581047008746,
  id: 4,
  course: "COmputer Science and mathemetics",
  techStack: "Javascript and python, css and html",
  …
} {
  createdAt: 1582538141524,
  updatedAt: 1582538141524,
  id: 5,
  course: "trrrt",
  techStack: "dddf",
  …
}]

const searchString = "sc"

I want a function whereby if any of the object keys be it, course, techStack or other ones contains the letter "sc", the object is returned in the array.

Just to buttress my point. I will show a function that does something similar but only handles the "course" object key.

 const filterResult = (array, query) => { const filterCriteria = el => el.course.toLowerCase().indexOf(query.toLowerCase()) !== -1; return array.filter(filterCriteria) };

Use Object.values() to get an array of all the values in the object, then use Array.prototype.some() to check if any of the values contain the search string.

 const filterResult = (array, query) => { query = query.toLowerCase(); const filterCriteria = el => Object.values(el).some(prop => typeof prop == 'string' && prop.toLowerCase().includes(query)); return array.filter(filterCriteria) }; const myArray = [{ createdAt: 1579147513645, updatedAt: 1579147513645, id: 3, course: "Test", techStack: "Test ", }, { createdAt: 1581047008746, updatedAt: 1581047008746, id: 4, course: "COmputer Science and mathemetics", techStack: "Javascript and python, css and html", }, { createdAt: 1582538141524, updatedAt: 1582538141524, id: 5, course: "trrrt", techStack: "dddf", }] const searchString = "sc" console.log(filterResult(myArray, searchString));

You can try this:

function toSearchableString(str) {
    return str ? str.trim().toLowerCase() : '';
}

const filterByTerm = (item, searchString) => toSearchableString(item).includes(toSearchableString(searchString));

 const filterData = (dataArray, searchString) => {
        const result = dataArray.filter(data => {
            const course = data.course ? filterByTerm(data.course, searchString) : false;
            const techStack = data.techStack ? filterByTerm(data.techStack, searchString) : false;
            // ... include here all object keys you want to be filtered based on searchString
            return course || techStack;
        });

        return result;
  };

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