0

I have a json response that looks like the image below. I want to get all dates from the json and store in an array.

  function buyOption(){
      var ticker = document.getElementById('ticker').value;

    fetch("https://stock-and-options-trading-data-provider.p.rapidapi.com/options/JPM", {
    
    .then(response => response.json())
    .then(data => {
      dataset = data;
      console.log(dataset['options'])
      loadTable()
      
    })

    .catch(err => {
      console.log(err);
    });


    function loadTable(){
      expiration_dates = []
      dates = dataset['options']
      // console.log(JSON.parse(dates))
      
      var keys = [];
        for(var k in dates) keys.push(k);
      console.log(keys)// returns ["0","1","2",3","5",6","9","10","11"]
  
      console.log(dates[0].value) // returns undefined 
      
    }


}
  
  

enter image description here

goal is to have expiration_dates = ["2020-08-21","2020-08-28"]

1
  • Can you add the actual JSON response you get from that API in the question please ? Commented Aug 17, 2020 at 4:15

5 Answers 5

2

You can try this. This will give you only the expiration dates.

var obj = {
  "options": [{
    "10-2-2001": "",
    "someOtherProp": ""
  }, {
    "20-2-2001": "",
    "someOtherProp": ""
  }]
}

var expDates = obj.options.map(o=>Object.keys(o)[0])

console.log(expDates)

Refs:

Array.map()

Object.keys()

Sign up to request clarification or add additional context in comments.

Comments

2

Try this

let result = dataSet.options.map(x => Object.keys(x));
console.log(result.flat(1))

Comments

1

A simple array map should do the trick and use Object.keys() array to get first key from each object in your data array

const dates = dataset['options'].map(o => Object.keys(o)[0])

console.log(dates)
<script>
const dataset = {
    options: [{
      '2013-12-22': {
        puts: [],
        calls: []
      }},
      {'2013-02-15': {
        puts: [],
        calls: []
      }},
     { '2018-01-01': {
        puts: [],
        calls: []
      }}
    ]

  }

</script>

Comments

0

Something like

const options=dates.options.map(o=>
  Object.keys(o).filter(k=>k.match(/^2\d{3}-\d{2}-\d{2}$/))[0]);

The idea is to loop over all options, get all keys for each of the objects and filter out the keys matching the Regexp, which is a date format, starting with 2. From the filtered keys-array I am only interested in the first element ([0]).

Comments

-1
for(k in dates) {
    keys.push((v=>{
        for(let i in v) return i;
    })(dates[k]));
}

Try it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.