JavaScript - Filter invalid entries from JSON

By IncludeHelp Last updated : January 27, 2024

Problem statement

Given a JSON with some valid and invalid entries, write JavaScript code to filter invalid entries from JSON.

Filtering invalid entries from JSON

To filter invalid entries from JSON, first write a callback function, and then use the Array.filter() method of Array object by passing the callback function. In the callback function, you can write code based on your conditions to filter out the entries. In below code, we are filtering empty, null, NaN, and undefined entries.

JavaScript code to filter invalid entries from JSON

This example filters invalid entries based on the employee id (empId).

// Creatung a JSON with emply empIDs
const arr = [
  { empID: 101 },
  { empID: 102 },
  { empID: 103 },
  { empID: 0 },
  { empID: 104 },
  {},
  { empID: null },
  { empID: NaN },
  { empID: "undefined" },
];

// Printing Data
console.log("Original records\n", arr);

// Counter variable to count invalid ids
let invalempIDEntries = 0;

function filterJSONByID(item) {
  if (Number.isFinite(item.empID) && item.empID !== 0) {
    return true;
  }
  invalempIDEntries++;
  return false;
}

// Filtering data
let result = arr.filter(filterJSONByID);

// Printing Data
console.log("Filtered records\n", result);

console.log("Number of Invalid Employee IDs =", invalempIDEntries);

Output

The output of the above code is:

Original records
 [
  { empID: 101 },
  { empID: 102 },
  { empID: 103 },
  { empID: 0 },
  { empID: 104 },
  {},
  { empID: null },
  { empID: NaN },
  { empID: 'undefined' }
]
Filtered records
 [ { empID: 101 }, { empID: 102 }, { empID: 103 }, { empID: 104 } ]
Number of Invalid Employee IDs = 5
Note

Never miss to write JavaScript code inside the <script>...</script> tag.

Also Learn: Where to place JavaScript Code?

To understand the above example, you should have the basic knowledge of the following JavaScript topics:

All JavaScript Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.