alex
alex

Reputation: 7601

How to make the following function return true or false?

The following function checks if some objects have the property thumbnail. And I want it to return true if the object has a thumbnail and false if the object doesn't:

function hasThumbnail (key, object) {
  Object.keys(object).forEach(key => {
    const value = object[key]
    if (value.constructor === Array) {
      value.forEach(obj => {
        if (obj.thumbnail) {
          return true
        } else {
          return false
        }
      })
    }
  })

However, right now the function doesn't return anything. How can I make the function return true or false?

Upvotes: 0

Views: 109

Answers (3)

georg
georg

Reputation: 214949

Here's a less verbose way:

function hasThumbnail(object) {
    return Object.values(object).some(prop =>
       Array.isArray(prop) && prop.some(x => x.thumbnail));
}

Object.values can be easily polyfilled.

Upvotes: 1

Paper
Paper

Reputation: 1313

You are having an forEach, but return in a loop just ends the loop so you need to do it like this:

function hasThumbnail (key, object)
{
    var ret = false;
    Object.keys(object).forEach(key => {
        const value = object[key]
        if (value.constructor === Array) {
            value.forEach(obj => {
                if (obj.thumbnail) {
                    ret = true;
                    return;
                } else {
                    ret = false;
                    return;
                }
            })
        }
    });
    return ret;
}

This code is untested and I'm more of a jQuery guy, but the concept of return not working in a loop should be the same with vanilla JS.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386520

You may use Array#some inside to get a true or false out of the iteration, if found.

function hasThumbnail (key, object) {
    return Object.keys(object).some(key => {
        const value = object[key]
        if (value.constructor === Array) {
            return value.some(obj => {
                return obj.thumbnail;
            });
        }
    });
}

Upvotes: 2

Related Questions