Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find index of empty object in array of object [duplicate]

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.

like image 725
narender saini Avatar asked Apr 18 '19 07:04

narender saini


3 Answers

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);
like image 97
Sebastian Kaczmarek Avatar answered Nov 07 '22 20:11

Sebastian Kaczmarek


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);
like image 2
Nina Scholz Avatar answered Nov 07 '22 20:11

Nina Scholz


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);
like image 1
Hien Nguyen Avatar answered Nov 07 '22 21:11

Hien Nguyen