cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Retrieve the key value by passing another key value in json

viji28
New Contributor

My Json looks like this ๐Ÿ™‚
{ โ€œmainโ€ :[
{
โ€œCMโ€: โ€œTโ€,
โ€œTMโ€: โ€œโ€
},
{
โ€œCMโ€: โ€œ100000โ€,
โ€œTMโ€: โ€œ9999โ€
},
{
โ€œCMโ€: โ€œ200000โ€,
โ€œTMโ€: โ€œโ€
} ]
}
This is stored in an test.expr file.

I have the CM values coming from the previous snap. What i would like to achieve is - I would like to pass 100000 to CM and retrieve 9999 as result.

How can I achieve this ?

1 ACCEPTED SOLUTION

del
Contributor III

@viji28,

If you have the liberty to restructure your test.expr expression library file, I would recommend moving to the match control operator syntax for reduced code and simpler reference. For the test.expr file, you could change it to:

{
    "main": cm => match cm {
       "T" => "",
       "100000" => "9999",
       "200000" => "",
       _ => ""
    }
}

After, you can use a simpler reference:

lib.test.main($CM)

However, if you canโ€™t make a major change to the structure for some reason, but can adapt it to an arrow function, you can incorporate bojanvelevskiโ€™s suggestion in the expression library and still use the simpler lib.test.main($CM) reference. The file might look something like this:

{ 
	"main": (cm =>
		[
			{
				"CM": "T",
				"TM": ""
			},
			{
				"CM": "100000",
				"TM": "9999"
			},
			{
				"CM": "200000",
				"TM": ""
			}
		].filter(x=> x.CM==cm)[0].TM)
}

There are other restructuring options, as well.

View solution in original post

4 REPLIES 4

bojanvelevski
Valued Contributor

Try this:

lib.test.main.filter(x=>x.CM == $CM)[0]

Tried this, Worked for me. Thank you so much!

del
Contributor III

@viji28,

If you have the liberty to restructure your test.expr expression library file, I would recommend moving to the match control operator syntax for reduced code and simpler reference. For the test.expr file, you could change it to:

{
    "main": cm => match cm {
       "T" => "",
       "100000" => "9999",
       "200000" => "",
       _ => ""
    }
}

After, you can use a simpler reference:

lib.test.main($CM)

However, if you canโ€™t make a major change to the structure for some reason, but can adapt it to an arrow function, you can incorporate bojanvelevskiโ€™s suggestion in the expression library and still use the simpler lib.test.main($CM) reference. The file might look something like this:

{ 
	"main": (cm =>
		[
			{
				"CM": "T",
				"TM": ""
			},
			{
				"CM": "100000",
				"TM": "9999"
			},
			{
				"CM": "200000",
				"TM": ""
			}
		].filter(x=> x.CM==cm)[0].TM)
}

There are other restructuring options, as well.

viji28
New Contributor

Tried this. Worked for me. Thank you so much!