0

I have a problem with this structure:

const ob = {
name: ''
ob: {}
arr: []
}

I want to check if all values, are empty. If I have only strings and arrays, the problem is trivial, but with an object my best solution is something like that,

const test = Object.values(ob).reduce((acc, curr) => {
    const isPlainObject = typeof curr === 'object' && !Array.isArray(curr);

    if (isPlainObject) !Object.values(curr).length ? (acc = false) : null;
    else !curr.length ? (acc = false) : null;

    return acc;
  }, true);

I'm not satisfied with this, did anybody face similar problem and can help me with that?

4
  • 3
    do not use a ternary operator to set a variable.... bad practice. Seems like you should be using some or every, not reduce. What if there is a number? Commented Apr 29, 2021 at 13:56
  • 1
    codereview.stackexchange.com Commented Apr 29, 2021 at 13:57
  • Are these the only empty values? Can the object have null, undefined or any other values that is considered as empty? isPlainObject will be true for null Commented Apr 29, 2021 at 13:59
  • @adiga thanks for that, I don't think it is possible to get null, or undef there, but I missed that :) Commented Apr 29, 2021 at 14:04

2 Answers 2

1

You could check the various types and then either the length or the count of (own enumerable) keys or the value.

const
    isEmpty = object => Object.values(object).every(v => {
        if (Array.isArray(v)) return v.length === 0;
        if (v && typeof v === 'object') return Object.keys(v).length === 0;
        return v === '';
    }),
    ob = { name: '', ob: {}, arr: [] };

console.log(isEmpty(ob));

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

Comments

1

Maybe not so much better than your solution, C233. But I'll give it a shot ;)

const isEmpty = (val) => {
    if(!val) {
        return true;
    }
    if (typeof val === 'object') {
        return Object.values(val).length === 0;
    }
    if (typeof val === 'string') {
        return val.length === 0;
    }
    return false;
}

const hasEmptyProps = (obj) => Object.values.map(isEmpty).reduce((result, curr) => result && curr, true);

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.