0

I need to find all objects in multiple arrays with a specific value, returning another value of this image of all matching objects.

I'll try to make it a bit clearer with an example. I'm searching for every target with the value find-me and get the source value returned. Some arrays have matching objects, some may not have. The result array should have unique values.

const deps = {
  "something": [
    {
      "type": "static",
      "source": "foo",
      "target": "bar"
    },
    {
      "type": "static",
      "source": "return-me",
      "target": "find-me"
    }
  ],
  "anything": [
    {
      "type": "static",
      "source": "and-me",
      "target": "find-me"
    }
  ],
  "no-match": [
    {
      "type": "static",
      "source": "foo",
      "target": "bar"
    }
  ]
}

So for this example, the result should be

['return-me', 'and-me']

I tried this:

const search = 'find-me'
const sources = Object
  .values(deps)
  .flat()
  .find(el => el.target === search)
  .map(el => el.source)

But of course this can't work, as find will give me only one result (which is an object). How do I get all results instead of first matching object?

2 Answers 2

1

Instead of using Array.find, you need to use Array.filter to get the matched results.

const deps = {
  "something": [
    {
      "type": "static",
      "source": "foo",
      "target": "bar"
    },
    {
      "type": "static",
      "source": "return-me",
      "target": "find-me"
    }
  ],
  "anything": [
    {
      "type": "static",
      "source": "and-me",
      "target": "find-me"
    }
  ],
  "no-match": [
    {
      "type": "static",
      "source": "foo",
      "target": "bar"
    }
  ]
};

const result = Object.values(deps)
  .flat()
  .filter(({ target }) => target === 'find-me')
  .map(({ source }) => source);
console.log(result);

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

Comments

1

Replace Array.find() with Array.filter() that can return multiple results:

const deps = {"something":[{"type":"static","source":"foo","target":"bar"},{"type":"static","source":"return-me","target":"find-me"}],"anything":[{"type":"static","source":"and-me","target":"find-me"}],"no-match":[{"type":"static","source":"foo","target":"bar"}]}

const search = 'find-me'
const sources = Object
  .values(deps)
  .flat()
  .filter(el => el.target === search)
  .map(el => el.source)
  
console.log(sources)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.