Issue
I am trying to validate a string against values stored in a database to check whether that string exists there.
Here is the JSON Object being retrieved:
{
"ArrayOfJobsModel": {
"JobsModel": [
{
"LongName": "WC389 - This is WC389 Job",
"Name": "WC389"
},
{
"LongName": "WC256 - The WC256 JO Description",
"Name": "WC256"
},
{
"LongName": "TT134 - The TT134 description",
"Name": "TT134"
}
]
}
}
Here I need to check whether a variable called jobNumber
exists as a Name in the JSON object.
And here is the part of the code where I attempt to retrieve the JSON object but I am not sure how to search it.
fetch('http://orhapi.azurewebsites.net/api/services/LoadJobs?type=all', {
method: 'GET',
header: {
'Content-Type': 'application/json',
},
}).then((response) => {
response.json();
}).then((myJson) => {
//not sure what to do here
}).catch((err)=>{
alert('could not connect to server')
});
if(this.state.numberExists){
this.props.navigation.navigate('StockItem',{jobNumber: this.state.jobNumber});
}
I need to check whether jobNumber
exists inside myJson
as a Name (e.g check if jobNumber == WC256
)
Edit:
Here is an attempt I tried but I can't figure out what's wrong with it:
then((responseJson) => {
responseJson.ArrayOfJobsModel.JobsModel.map((job, index)=>{
if(job.Name == this.state.jobNumber){
this.state.numberExists;
}
}
Solution
You can use the map
method to search a term in your array of objects.
for example -
let itemFound = false;
ArrayOfJobsModel.JobsModel.map((job, index) => {
if(job.Name == 'Your search string'){
itemFound = true;
}
});
Answered By - Alok Mali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.