0

I want to check if objects within an array is empty or not. This is how I receive my data and the object length is dynamic so I cannot use any hard coded condition.

[{},{},{},{},{},{},{},{},{},{}] // length is dynamic

I have ways liek:

 Object.keys(myarray[0]).length === 0; //but this applies only for object.

is there an elegant way of checking this in one condition by any chance?

1
  • 1
    Do you want to check if at least 1 object in the array is empty or if there are more than one object in the array empty Commented Aug 25, 2020 at 2:03

3 Answers 3

3

To detect if there are any empty objects in your array, use Array.prototype.some() combined with Object.keys() and Array.prototype.length

const anyEmptyObjects = myarray.some(o => Object.keys(o).length === 0)

To retrieve the empty objects, use the same predicate with Array.prototype.filter()

const emptyObjects = myarray.filter(o => Object.keys(o).length === 0)
Sign up to request clarification or add additional context in comments.

Comments

2

What about Object.entries? Though I suppose that's not much different

let a = [{},{test:1},{},{},{test:2},{},{},{test:3},{},{}];
let result = a.map((ele) => (Object.entries(ele) == 0));

output

[true, false, true, true, false, true, true, false, true, true]

Comments

1

To complete @jmp 's solution you can get the final answer of hasEmapty like this:

const hasEmpty = arr => arr.reduce((acc, obj)=> acc || !Object.entries(obj).length, false)


//---

let a = [{},{test:1},{},{},{test:2},{},{},{test:3},{},{}];
let b = [{test: 3}, {test: 4}, {test: 5}]
let c = [{},{}]
let d = []

console.log(hasEmpty(a))
console.log(hasEmpty(b))
console.log(hasEmpty(c))
console.log(hasEmpty(d))

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.