Home > Blockchain >  Taking the first JSON string that contains a specific phrase (Javascript)
Taking the first JSON string that contains a specific phrase (Javascript)

Time:01-23

I am trying to get the value of the first string in JSON containing the string amogus. I have no idea how to start.

I want it to get the first JSON string that has amogus in it, then take the entire string, including the number included in the found string.

JSON file:

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

As you can see, the JSON file contains multiple strings, and some of them contain amogus. My desired output is amogus1208, which is the first string containing amogus.

Does anybody know how this could be done? Thanks.

CodePudding user response:

You can use Array.find() to find the first matching item and use String.includes() to check the items in the callback function in find(), as follows:

const data = ["hosds29083", "amogus1208", "amogus1213"];

const firstOne = data.find(str => str.includes('amogus'));

console.log(firstOne)

CodePudding user response:

Get the JSON content into an array then use .find() on it.

  • Related