简体   繁体   中英

How do I filter out null entries in an array of objects?

I'm just learning JavaScript, and I was trying to understand this example of filter() on Mozilla , but I don't get how this example works, because when I try to do the same thing on my example, it just returns an empty array.

Here's the example from the link:

var arr = [
  { id: 15 },
  { id: -1 },
  { id: 0 },
  { id: 3 },
  { id: 12.2 },
  { },
  { id: null },
  { id: NaN },
  { id: 'undefined' }
];

var invalidEntries = 0;

function filterByID(obj) {
  if ('id' in obj && typeof(obj.id) === 'number' && !isNaN(obj.id)) {
    return true; // <--- WHY? 
  } else {
    invalidEntries++;
    return false;
  }
}

var arrByID = arr.filter(filterByID);

console.log('Filtered Array\n', arrByID); 
// Filtered Array
// [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }]

console.log('Number of Invalid Entries = ', invalidEntries); 
// 4

This is my example:

obj = [{0: 31}, {1: null}, {2: null}, {3, 28}]

function isNotNull(obj) {
    for (var prop in obj) {
        if (obj.prop != null) {
            return true;
        }
    } 
}

console.log(ages.filter(isNotNull)) // -> []

To quote the page you linked:

callback Function to test each element of the array. Invoked with arguments (element, index, array). Return true to keep the element, false otherwise.

true as return value means the object will be accepted in the result set. false means it is considered invalid.

you need to use array syntax to dynamically lookup properties:

ages = [{0: 31}, {1: null}, {2: null}, {3: 28}]

    function isNotNull(obj) {
        for (var prop in obj) {
            if (obj[prop] != null) {
                return true;
            }
        } 
    }

    console.log(ages.filter(isNotNull)) // -> [{"0":31},{"3":28}]

note the obj[prop] instead of obj.prop

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