How to selectively retrieve value from json output JavaScript

We have the following data inside a json file data.json


   "names": [{
      "name": "Ramesh",
      "readable": true
   }, {
      "name": "Suresh",
      "readable": false
   }, {
      "name": "Mahesh",
      "readable": true
   }, {
      "name": "Gourav",
      "readable": true
   }, {
      "name": "Mike",
      "readable": false
   } ]

Our job is to create a function parseData that takes in the path to this file as one and only argument, reads this json file, and returns an sub array of names array where the property readable is true.

Now, let’s write the code for this, we will use the require module to fetch the json data and then return a filtered array like this −


const path = "./data.json";
const parseData = (path) => {
   const data = require(path);
   //no need to parse the data as it is already parsed
   return data.names.filter(el => el.readable);
const results = parseData(path);


The console output will be −

   { name: 'Ramesh', readable: true },
   { name: 'Mahesh', readable: true },
   { name: 'Gourav', readable: true }

Updated on: 24-Aug-2020


Kickstart Your Career

Get certified by completing the course

Get Started