Home > Enterprise >  Is there a way to pass keys into a JavaScript array where a a string might match multiple values of
Is there a way to pass keys into a JavaScript array where a a string might match multiple values of

Time:05-06

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.

CodePudding user response:

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);

CodePudding user response:

Use Object.keys() to get an array of keys, and filter them with Array.filter(). In the filter's predicate function take the relevant value from the object using the key - obj[key] and compare it to str.

const str = 'foo'

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

const keys = Object.keys(obj).filter(key => obj[key] === str)

console.log(keys)

CodePudding user response:

You could get all the entries like you are doing, but instead of using find, filtering all the entries with the value on str that you want to find and mapping it to a list. Like this:

const str = "foo";

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

const repeated = Object.entries(obj)
  .filter(([key, val]) => val === str)
  .map(([key, val]) => key);

console.log(repeated);

CodePudding user response:

Another way:

const obj = {
  quay: "foo",
  key1: "blargh",
  yaya: "foo",
  idnet: "blat",
  blah: "foo",
  hahas: "blargh"
}
let items = Object.fromEntries(Object.entries(obj).filter(([key, val]) => val === 'foo'));
console.log(Object.keys(items))

  • Related