1

TLDR; How would you go about making a function that e.g. search for value e.g. in array, but where the property searched for can change?

Example.

    const search = (arr, text) =>
    {
        // What if rather than e.name we wanted to search on e.phone?
        // And how could this be passed with the function params?
        return arr.find(e => e.name === text)
    }

3
  • 3
    You can use bracket notation to access any property. See here: Dynamically access object property using variable Commented Dec 4, 2020 at 14:40
  • Oh wow, I had no idea that was even a thing. Thank a lot man :) Commented Dec 4, 2020 at 14:42
  • 1
    Add another parameter (arr, prop, text) and use e[prop] === text Commented Dec 4, 2020 at 14:44

1 Answer 1

1

You can use Array#reduce to find a nested property (passed in as a string) to compare with the text.

const search = (arr, prop, text) =>{
  const getProp = obj => prop.split('.').reduce((acc,curr)=>acc?.[curr], obj);
  return arr.find(e => getProp(e) === text);
}
console.log(search([{a: 1}, {a: {b: 'test'}}], 'a.b', 'test'));
console.log(search([{name: 'Joe'}, {name: 'John'}, {name: 'Bob'}], 'name', 'Bob'));

Sign up to request clarification or add additional context in comments.

4 Comments

I think OP is looking for a way to make a filter function that is not associated with only 1 key in object
@Rajesh Are they not looking for a way to search a dynamic property?
@Rajesh - I was yes, OrAssayag posted the solution.
I support this anwer . Simple and short.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.