0

I have an object that looks like this:

 steps: {
        '36793745-4c52-42d2-91a5-dcdc9de2e8fa': [],
        'b23d8770-806f-44a9-aa2e-a21dd68f7977': [],
        '33571d58-b833-4a7d-a1a1-ec96366cb74a': [],
        'b1499917-7f82-49e5-9708-6237340a9610': []
      }

Each array within that object can be an array of strings.

I'd like to check if any of those arrays have an item, if they do, I like to return true.

I do not care about checking any after, as soon as one returns true, I am happy.

I tried something like Object.keys(steps).map(step => steps[step].length > 0) but this returns an array of true or false [false, false, false, false]

I then tried Object.keys(steps).filter(step => steps[step].length > 0) but this returns an array of the item keys that do have a value.

I know at this point I could simply check the length of the result but I was wondering if there is a better way to achieve this.

This object could potentially grow in size considerably, so I was hoping for some sort of early exit as soon as I get a true

2 Answers 2

2

You could use the values and a check for the length of the array.

var hasItems = Object.values(steps).some(array => array.length);
Sign up to request clarification or add additional context in comments.

Comments

0

Use some.

It can be used to check if at least one element in the array passes a condition or not. Like Array.Filter, it accepts a test function where it loops through the source array’s element.

It returns true if any one of the element passes the test condition. If all the elements fails on the test function, it returns false. it short circuits the loop as soon as one of element passes the test function.

const stepHasProp = Object.values(steps).some(array => array.length)

1 Comment

Thank you, I wasn't aware of some - you broke it down perfect :)

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.