简体   繁体   中英

Javascript get key of nested JSON object?

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 
      
    }


}
  
  

在此处输入图像描述

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

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()

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>

Try this

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

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] ).

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

Try it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM