Pawan
Pawan

Reputation: 32321

How to fetch Corresponding JSON Array

I have got the following JSON as shown below

{
    "results": ["BANKNIFTY", "NIFTY", "NIFTYIT"],
    "NIFTY": ["31-Mar-2016", "28-Apr-2016", "26-May-2016", "30-Jun-2016", "29-Sep-2016", "29-Dec-2016", "29-Jun-2017", "28-Dec-2017", "28-Jun-2018", "27-Dec-2018", "27-Jun-2019", "26-Dec-2019", "25-Jun-2020", "31-Dec-2020"],
    "NIFTYIT": ["31-Mar-2016", "28-Apr-2016", "26-May-2016"],
    "BANKNIFTY": ["31-Mar-2016", "28-Apr-2016", "26-May-2016"]
}

In case the key is passed how to fecth the corresponding array

For example if NIFTYIT is passed as input the output should be

["31-Mar-2016", "28-Apr-2016", "26-May-2016"]

This is my fiddle

https://jsfiddle.net/x4yh4831/2/

Could you please let me know how to do this ???

Upvotes: 0

Views: 41

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly note that your code example is dealing with objects; no part of it is JSON.

To solve your actual problem you can use bracket notation to access the properties of an object via a key stored in a variable. Try this:

var extractfor = 'BANKNIFTY';
var results = myjson[extractfor]
console.log(results); // = ["31-Mar-2016", "28-Apr-2016", "26-May-2016"]

Updated fiddle

Upvotes: 2

Related Questions