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

Time:01-23

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.

CodePudding user response:

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.

CodePudding user response:

Here is a possible Solution:

const json = JSON.parse(data);
const first = json.stuff.find(obj => obj.includes("your string"))

CodePudding user response:


const json = `{
  "stuff": ["hosds29083", "amogus1208", "amogus1213"]
}`
const data = JSON.parse(json)
const findData = data.stuff.find(s=>s.includes("amogus"))
console.log(findData)

CodePudding user response:

const foundString = yourParsedJsonObject.stuff.find(string => string.includes("amogus"))
  • Related