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)
    }
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Ills
  • 415
  • 1
  • 3
  • 13
  • 3
    You can use bracket notation to access any property. See here: [Dynamically access object property using variable](https://stackoverflow.com/q/4244896) – VLAZ Dec 04 '20 at 14:40
  • Oh wow, I had no idea that was even a thing. Thank a lot man :) – Ills Dec 04 '20 at 14:42
  • 1
    Add another parameter `(arr, prop, text)` and use `e[prop] === text` – adiga Dec 04 '20 at 14:44

1 Answers1

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'));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80