How do you handle accessing the objects inside a JSON response when the key is dynamic?
In my code sample, I've created a reducer that makes API calls but requires params to work:
import { fetchAPI } from '../lib/api'
export async function resultsReducer(dataType, sortParam, nodeFields) {
let allResults = []
let fetch = await fetchAPI(`
query {
${dataType} (sortBy: ${sortParam}) {
pageInfo {
hasNextPage
startCursor
endCursor
}
edges {
node {
${nodeFields}
}
cursor
}
totalCount
}
}
`)
// How I access the dataType key - this doesn't work
fetch.dataType.edges.map( (item) => {
allResults.push(item)
})
}
That function works and it returns a response that gets deposited on fetch
that looks like this:
{
allLocationss: {
pageInfo: {
hasNextPage: true,
startCursor: 'YXJyYXljb25uZWN0aW9uOjA=',
endCursor: 'YXJyYXljb25uZWN0aW9uOjE5'
},
edges: [
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object]
],
totalCount: 52
}
}
In my example response, allLocationss
is the key, but some times it's allTopics
or allEvents
, etc. If I use Object.keys(fetch)[1]
I get a string returned. I also tried fetch.Object.keys(fetch)[1].edges
but that doesn't work either. Would love some ideas SO
To access dynamic key in response use variable[key]
notations
// How I access the dataType key?
fetch[dataType].edges.map((item) => {
allResults.push(item);
});
You can use bracket notation to access the key with dataType
's value:
fetch[dataType]
Since map()
already creates an array, you don't need to declare allResults.push()
. Instead, just use the array returned by map()
:
const allResults = fetch[dataType].edges.map(item => item);
In fact, if you don't need a copy of the array, you can just assign directly:
const allResults = fetch[dataType].edges;
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.