1

I have an object that looks like this:

objectProp = {
  property1: [],
  property2: [],
}

I want to check if all properties(that are string arrays) if this object are null and return true. I am for some reason stuck. How can I do this? I am using "target": "es2015"

I tried this but does not work:

 if (!Object.keys(this.objectProp).every(array => array.length > 0)) {
      console.log('all are empety');
    }
Kathrine Hanson
  • 575
  • 2
  • 10
  • 32
  • Does this answer your question? [How to Check if Arrays in a Object Are All Empty?](https://stackoverflow.com/questions/39919560/how-to-check-if-arrays-in-a-object-are-all-empty) – Heretic Monkey Feb 25 '20 at 14:59

4 Answers4

5

You need to use Object.values(this.objectProp) instead of Object.keys(this.objectProp) for this to work. As Object.keys method returns an array of a given object's own enumerable property names and Object.values method returns an array of a given object's own enumerable property values, which is actually what you are looking for.

let objectProp = {
  property1: [],
  property2: [],
}

console.log(Object.keys(objectProp))

console.log(Object.values(objectProp))

For Es2015, you can try this:

let obj = {
  property1: [],
  property2: [],
}

// Log is print only when all arrays are empty
if (Object.keys(obj).map(e => obj[e]).every(a => a.length === 0)) {
  console.log('all are empty');
}
palaѕн
  • 72,112
  • 17
  • 116
  • 136
2

By using Object.keys() you can do it as following

var objectProp = {
  property1: [],
  property2: [],
}

if(Object.keys(objectProp).every(key => objectProp[key] && objectProp[key].length === 0)){
  console.log('All is empty')
}
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
2

You should use Object.values as follow:

if (!Object.values(this.objectProp).every(({length}) => Boolean(length))) {
  console.log('all are empety');
}
Ele
  • 33,468
  • 7
  • 37
  • 75
0

Most answers seem to have missed the part about your logic been slightly wrong. They will say empty, if only single item is empty,. This is because the logic is !every > 0 But switching this logic to every <= 0 will get what you want.

eg.

The below example will return true, true for the broken version. But true, false for the fixed one.

var objectProp = {
  property1: [],
  property2: [],
};

var objectProp2 = {
  property1: [],
  property2: [],
  property3: ['not empty']
};


function allIsEmptyBroken(objectProp) {
  return (!Object.keys(objectProp).every(key => objectProp[key] && objectProp[key].length > 0));
}

function allIsEmptyFixed(objectProp) {
  return (Object.keys(objectProp).every(key => objectProp[key] && objectProp[key].length <= 0));
}


console.log('allIsEmptyBroken');
console.log(allIsEmptyBroken(objectProp));
console.log(allIsEmptyBroken(objectProp2));

console.log('allIsEmptyFixed');
console.log(allIsEmptyFixed(objectProp));
console.log(allIsEmptyFixed(objectProp2));
Keith
  • 22,005
  • 2
  • 27
  • 44