简体   繁体   中英

How to Check for an empty object property in an array of objects in Javascript

In my application i am having a data which is an array of objects.if any of the object property in any of the objects in the array is empty,then the data should not be saved. consider the sample data below, how to loop through all the objects in the array and check for any empty value.in below data the third object has an empty fname propety,how to find empty object properties like that

var obj = [{fname:"name1",lname:"lname1"},
           {fname:"name2",lname:"name2"},
           {fname:"",lname:"name3"}
          ];

you can get a list of all values in an object using Object.values() . You can use filter() to filter elements from an array. Combining these two you can do something like this:

You can also keep an array of all the values you don't want and then check if any of these exist in object values that you are filtering.

 var obj = [{fname:"name1",lname:"lname1"}, {fname:"name2",lname:"name2"}, {fname:"",lname:"name3"}, {fname:null,lname:"name4"}]; var filterobj = obj.filter(function(o){ var values = Object.values(o); var arr2 = ["", null]; //array of values you don't want. if(arr2.some(function (val) { return values.indexOf(val) >= 0; })) //checks if atleast one value of arr2 is in values. return false; else return true; }); console.log(filterobj); 

You can use Array.reduce to reduce the array to only the elements that have a non empty fname

 var obj = [{fname:"name1",lname:"lname1"}, {fname:"name2",lname:"name2"}, {fname:"",lname:"name3"}, {fname:null,lname:"name4"}]; var goodNames = obj.reduce(function (notEmptyNames, name) { if (name.fname) notEmptyNames.push(name); return notEmptyNames; }, []); console.log(goodNames); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM