I would like to retrieve option with key '2021-05-14' from this json-object.
{
stock: {
zip: '95014',
lastUpdated: '05/02/2021'
},
options: [
{ '2021-05-07': [Object] },
{ '2021-05-14': [Object] },
{ '2021-05-21': [Object] },
{ '2021-05-28': [Object] },
{ '2021-06-04': [Object] },
{ '2021-06-18': [Object] }
]
}
I tried:
var options;
var expirationSeries;
options = res.body.options; // res.body is the json-object
for (var key in options)
{
if (key=='2021-05-14') {
expirationSeries = options[key];
};
}
console.log(expirationSeries);
but then I get error 'undefined'.
How to do this properly?
console.log(key)to see what it returns? You need to loop through the array and check if each object has the key'2021-05-14'optionscollection is not important, you could turn this into an object instead of an array, and simply haveoptions{'2021-05-07': [Object],'2021-05-14': [Object],'2021-05-21': [Object]}, achieving what you want to do simply usingoptions['2021-05-14']console.logto see what you're getting. Note thatfor (var k in ["first", "second"]) {will give0, 1so I think you'll find that key is a number.