Encountered an odd behavior while using fetch.
Take a look at this screenshot for the correct lengths and structures: console screenshot
Let's examine the JSON response from a server, where the likes
array has one object, and the comments
array has two:
{
"status":"success",
"payload":{
"272699880986":{
"likes":[
{
"createdTime":"2016-11-07T04:41:21.000Z",
"senderId":10209615042475034,
"senderName":"Alfredo Re",
"likes":1
}
],
"comments":[
{
"createdTime":"2016-11-07T04:41:54.000Z",
"senderId":1021426764639564,
"senderName":"Alfredo J. Re",
"comments":1
},
{
"createdTime":"2016-11-07T04:41:24.000Z",
"senderId":10209615042475034,
"senderName":"Alfredo Re",
"comments":1
}
]
}
}
}
When passing the response through response.json()
, it returns the following:
fetch('http://example.com/entries.json', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
...authKeys,
}
})
.then(response => {
switch(response.status){
case 200:
console.log('status 200', response)
return response.json()
}
})
.then(json => {
console.log('parsed response')
console.log(json)
})
The result of this operation is confusing:
{
"status":"success",
"payload":{
"272699880986":{
"likes":[
{
"createdTime":"2016-11-07T04:41:54.000Z",
"senderId":1021426764639564,
"senderName":"Alfredo J. Re",
"likes": 1,
"comments":1
},
{
"createdTime":"2016-11-07T04:41:24.000Z",
"senderId":10209615042475034,
"senderName":"Alfredo Re",
"comments":1
}
],
"comments":[
{
"createdTime":"2016-11-07T04:41:54.000Z",
"senderId":1021426764639564,
"senderName":"Alfredo J. Re",
"comments":1
},
{
"createdTime":"2016-11-07T04:41:24.000Z",
"senderId":10209615042475034,
"senderName":"Alfredo Re",
"comments":1
}
]
}
}
}
The likes
and comments
collections got mixed up. It's really frustrating. Am I missing something here?
UPDATE
Check out this gif showing chrome's console with arrays containing one and two objects respectively. Clicking on them transforms the former into an array with two objects! This is mind-boggling.