JavaScript search with dynamic parameters?

  • 0
    Hi guys.
    Tell me how to make a search in an object with dynamic parameter conditions?
    Here is my object.
    [{"prop":{"color":{"value":10},"diametr":{"value":15},"size":{"value":2}},"name":"результат 1"},{"prop":{"color":{"value":15},"diametr":{"value":17},"size":{"value":8}},"name":"результат 2"},{"prop":{"color":{"value":19},"diametr":{"value":17},"size":{"value":8}},"name":"результат 3"}]


    Find by one parameter, no problem.
    But I don’t understand how to make a dynamic filter by two or more parameters.
    Suppose in one case I need to find "size" == 8, as I said, not a problem. But to find "size" == 8 and "color" == 15, at the same time, I have a problem. Because size and color are dynamic parameters, diametr can be added to them.
    JavaScript Anonymous, May 3, 2020

  • 2 Answers
  • 0
    const data = [
    {"prop":{"color":{"value":10},"diametr":{"value":15},"size":{"value":2}},"name":"результат 1"},
    {"prop":{"color":{"value":15},"diametr":{"value":17},"size":{"value":8}},"name":"результат 2"},
    {"prop":{"color":{"value":19},"diametr":{"value":17},"size":{"value":8}},"name":"результат 3"}
    ]

    const search = filter =>
    Object.entries(filter).reduce((agg, [key, value]) =>
    agg.filter(v => v.prop[key].value === value)
    , data)


    console.log(search({ size: 8 }).map(v => v.name)) // ["результат 2", "результат 3"]
    console.log(search({ size: 8, color: 15 }).map(v => v.name)) // ["результат 2"]
    Anonymous

  • 0
    Before I could answer, I was distracted. Okay, I'll post my version anyway:

    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!