Use .find() on a JSON file to get a a string with a specific keyterm

I’m trying to use array.find() to get the first JSON string that contains amogus. I’ve tried to read the JSON file using fs then using JSON.parse() to make it readable. However, I can’t seem to get it to do what I want it to do.

JSON file:

{stuff: ["hosds29083", "amogus1208", "amogus1213"]

desired output: amogus1208

Thanks.

>Solution :

You can use the fs module in Node.js to read the JSON file, then use JSON.parse() to parse the file contents into a JavaScript object. Once you have the object, you can use the Array.prototype.find() method to find the first element in the "stuff" array that contains "amogus". Here’s an example:

const fs = require('fs');

fs.readFile('path/to/file.json', 'utf8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }

  const json = JSON.parse(data);
  const result = json.stuff.find(item => item.includes('amogus'));
  console.log(result); // amogus1208
});

You should replace path/to/file.json with the actual path to the JSON file you want to read.

Leave a Reply