I have an http request that calls an api and returns something that looks like this in the body. I need to access the "members" array. body.results
is undefined. What am I doing wrong?
The call to get this data looks like this:
http.get(options, function(error, response, body)
Results below:
{ results: [ { members: [Array] } ],
performanceStats:
{ inspectedCount: 2213,
omittedCount: 0,
matchCount: 828,
wallClockTime: 101 },
metadata:
{ eventTypes: [ 'SomeType' ],
eventType: 'SomeType',
openEnded: true,
beginTime: '2020-01-06T10:36:48Z',
endTime: '2020-01-07T10:36:48Z',
beginTimeMillis: 1578307008262,
endTimeMillis: 1578393408262,
rawSince: '1 DAYS AGO',
rawUntil: 'NOW',
rawCompareWith: '',
guid: '728c90b2-9637-cd72-26b3-8e05a6fa6fba',
routerGuid: '969d2d3a-e77c-db66-9a4a-c0141a516404',
messages: [],
contents: [ [Object] ] } }
asked Jan 7, 2020 at 10:48
3 Answers 3
JSON Response
{ results: [ { members: [Array] } ],
performanceStats:
{ inspectedCount: 2213,
omittedCount: 0,
matchCount: 828,
wallClockTime: 101 },
metadata:
{ eventTypes: [ 'SomeType' ],
eventType: 'SomeType',
openEnded: true,
beginTime: '2020-01-06T10:36:48Z',
endTime: '2020-01-07T10:36:48Z',
beginTimeMillis: 1578307008262,
endTimeMillis: 1578393408262,
rawSince: '1 DAYS AGO',
rawUntil: 'NOW',
rawCompareWith: '',
guid: '728c90b2-9637-cd72-26b3-8e05a6fa6fba',
routerGuid: '969d2d3a-e77c-db66-9a4a-c0141a516404',
messages: [],
contents: [ [Object] ] } }
To access members
body.results[0]
answered Jan 7, 2020 at 11:03
Comments
let c = { results: [ { members: [2,3] } ],
performanceStats:
{ inspectedCount: 2213,
omittedCount: 0,
matchCount: 828,
wallClockTime: 101 },
metadata:
{ eventTypes: [ 'SomeType' ],
eventType: 'SomeType',
openEnded: true,
beginTime: '2020-01-06T10:36:48Z',
endTime: '2020-01-07T10:36:48Z',
beginTimeMillis: 1578307008262,
endTimeMillis: 1578393408262,
rawSince: '1 DAYS AGO',
rawUntil: 'NOW',
rawCompareWith: '',
guid: '728c90b2-9637-cd72-26b3-8e05a6fa6fba',
routerGuid: '969d2d3a-e77c-db66-9a4a-c0141a516404',
messages: [],
contents: [ [Object] ] } }
console.log(c.results[0].members)
I keep ur response to variable c
Then first i call the c
then call the results
after that there is one object only so i use [0]
then call the members
Hope it helps
answered Jan 7, 2020 at 10:58
Comments
You need to access the response body as response.data.results
answered Jan 7, 2020 at 10:50
Comments
lang-js
body
is?body
, otherwise it's really difficult to tell what you're doing wrong? If you include that code in your question it would be helpful.body
may just be a string that contains the JSON. Maybe tryconst bodyParsed = JSON.parse(body);
and then check ifbodyParsed.results
is the arrayresults
is an array so members is at 0th index. trybody.results[0]
async await
orcallback
since network requests are asynchronous. If you are not waiting for the response to come then you will getundefined
.