Home > Net >  How to search an array of objects with a keyword that can match values to more than one property usi
How to search an array of objects with a keyword that can match values to more than one property usi

Time:04-23

const heroes = [
  {name: "Batman", realName: "Bruce Wayne", universe: "DC"},
  {name: "Superman", realName: "Clark Kent", universe: "DC"},
  {name: "Iron Man", realName: "Tony Stark", universe: "Marvel"},
  {name: "Star Lord", realName: "Peter Quill", universe: "Marvel"},
  {name: "Venom", realName: "Eddie Brock", universe: "Marvel"}
]

function search(lookup){
  const result = heroes.filter(each => {
    return each.name.toLowerCase().includes(lookup.toLowerCase())  || 
           each.universe.toLowerCase().includes(lookup.toLowerCase())
  })
  return result
}
console.log(search("DC"))

If I search by name "Batman" I will return the first object. If I search "DC" I will return the first two objects. I'm getting the results I want but what other ways can I iterate over heroes instead of using the || operator? If I wanted to also search by realName I would have to add another return value and I would appreciate input on how to achieve this.

CodePudding user response:

It seems like you're searching for a way to look at all of the values within a given object. This would be a great place to use Object.values(), which returns an array of each value in the object, so your first object would look like:

["Batman", "Bruce Wayne", "DC"]

Great! Now if you have a search term, let's call it lookup for ease of examples, you can loop through (or use the .includes() JS functionality like you did) this array you create with Object.values() like so:

const result = heroes.filter(each => {
    let objectValues = Object.values(each);

    return objectValues.includes(lookup);
})

I took out some portions of your code like the greater function of this snippet and how you are making doing the comparisons with lowercased strings, but I leave that as a challenge.

CodePudding user response:

Try this:

function search(lookup){
    return heros.filter(hero =>{
           return Object.values(hero).filter(value => value.includes(lookup))
        })
   }

CodePudding user response:

I think this could help you, it works with just parts of those names too:

const typedWord = "DC"; 
const list = [{name: "Batman", company: "DC"}, {name: "Spiderman", company: "Marvel"}]

const filteredList = list.filter(function (object) {
    const entries = Object.entries(object).map((entry) => { return entry[0] })
    var matches = entries.filter((entry) => { return object[entry].includes(typedWord) })
    return matches.length !== 0
})
  • Related