Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access a json array element without using index number?

I have the following JSON:

{
   "responseObject": {
   "name": "ObjectName",
   "fields": [
   {
     "fieldName": "refId",
     "value": "2170gga35511"
   },
   {
     "fieldName": "telNum",
     "value": "4541885881"
   }]}
}

I want to access "value" of the the array element with "fieldName": "telNum" without using index numbers, because I don't know everytime exactly at which place this telNum element will appear.

What I dream of is something like this:

jsonVarName.responseObject.fields['fieldname'='telNum'].value

Is this even possible in JavaScript?

like image 321
schlingel Avatar asked Feb 08 '23 12:02

schlingel


1 Answers

You can do it like this

var k={
   "responseObject": {
   "name": "ObjectName",
   "fields": [
   {
     "fieldName": "refId",
     "value": "2170gga35511"
   },
   {
     "fieldName": "telNum",
     "value": "4541885881"
   }]
}};
value1=k.responseObject.fields.find(
function(i)
{return (i.fieldName=="telNum")}).value;
console.log(value1);
like image 147
Roli Agrawal Avatar answered Feb 10 '23 22:02

Roli Agrawal