How to selectively retrieve value from json output JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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

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 −

Example

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);
console.log(results);

Output

The console output will be −

[
   { name: 'Ramesh', readable: true },
   { name: 'Mahesh', readable: true },
   { name: 'Gourav', readable: true }
]
raja
Published on 24-Aug-2020 10:08:16
Advertisements