'How do I search for a string in an array from a .json file?
I have a config.json file, which looks like this (sample data for now):
{
"strings": {
"1": "one",
"2": "two",
"3": "three",
"4": "four",
"5": "five"
}
}
In my index.js file (i'm using node.js), How do I collect these into some form of array, and then see if a certain string is in there somewhere?
This is my code at the moment: (i've added in comments to show what I think each bit should do)
//import config.json
const config = require('./config.json');
//variables used later
var cyclecount = 0
hasPassed = false
//make an array from the strings section of the config.json file
myArray = config.strings;
//function that can be called later that compares a string to the array and checks if it's in it
function checkFor(string, times) {
//if the string is the same as the entry at that position of the array, log true to the console, and change the haspassed variable to true
if (string = myArray[times]) {
console.log('TRUE')
hasPassed = true
}
//if it's not, log false, and call the function again but with the times variable one lower than last time
else {
console.log('FALSE')
cyclecount = (times - 1)
checkFor(string, cyclecount);
}
}
//run the function, tell it to search for the string 003245 (which isn't in the array), and tell it that there's 10 enteries in the array.
checkFor('003245', 10)
//after the function has run, log if the haspassed variable is true or false
if (hasPassed = true) {
console.log('well done')
}
else {
console.log('no')
}
Even though the string it should be searching for is not in the array, it always finds it on the 6th run.
here's what it logs:
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
well done
Basically (if I haven't explained enough already), I'd like it to check if a given string is in the 'strings' section of the config.json file, and then set a variable to either true or false, depending on the outcome.
note: i'm quite new to all of this, if you can, please explain so I can understand easily :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
