Access Javascript Object Value with Dynamic Key

Tags: , ,



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 S.O.

Answer

To access dynamic key in response use variable[key] notations

// How I access the dataType key?
fetch[dataType].edges.map((item) => {
  allResults.push(item);
});


Source: stackoverflow