Skip to content
Advertisement

Is there a way to pass keys into a JavaScript array where a a string might match multiple values of an object?

So, if I have only one key to match, then something like:

    var str = "foo";

    let [key,val] = Object.entries(obj).find(([key,val]) => val== str);
    return key;

would work beautifully. But is there a way to add multiple keys if the value matches?

To give example of an object that might match the above string:

    obj = {
      quay: "foo",
      key1: "blargh",
      yaya: "foo",
      idnet: "blat",
      blah: "foo",
      hahas: "blargh"
    }

What I want to do is return all of the “foo” keys (quay, yaya, and blah) based on the matching var str from above.

I’m sure the answer is something simple I’m overlooking.

Advertisement

Answer

Use filter instead of find and map to remove the values.

const obj = { quay: "foo", key1: "blargh", yaya: "foo", idnet: "blat", blah: "foo", hahas: "blargh" }

const str = 'foo';

const keys = Object.entries(obj).filter(([, val]) => val === str).map(([key]) => key);
console.log(keys);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement