If I have an array like [{a:'b'},{}] and if I try to find an index of element {}. Then I am unable to get the correct index.
I have tried indexOf,findIndex and lodash's findIndex but all is returning -1 instead of 1 maybe because of reference.
The actual index should be 1 instead of -1.
You can make use of findIndex
and Object.keys()
:
const arr = [{a:'b'}, {}];
const emptyIndex = arr.findIndex((obj) => Object.keys(obj).length === 0);
console.log(emptyIndex);
If you search for an empty object, you search for the same object reference of the target object.
You could search for an object without keys instead.
var array = [{ a: 'b' }, {}] ,
index = array.findIndex(o => !Object.keys(o).length);
console.log(index);
You can use Object.keys(obj).length === 0 && obj.constructor === Object
for check empty object.
var a = [{a:'b'},{}]
var index;
a.some(function (obj, i) {
return Object.keys(obj).length === 0 && obj.constructor === Object ? (index = i, true) : false;
});
console.log(index);
var a = [{a:'b'},{}]
var index;
a.some(function (obj, i) {
return Object.keys(obj).length === 0 && obj.constructor === Object ? (index = i, true) : false;
});
console.log(index);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With