Search code examples
javascriptarraysobjectreact-context

How do I get the keys from an object in JavaScript?


I'm having difficulty working with an object returned by a GraphQl call to dynamoDB. I've given each nested object a number for a key. It's the number I'm trying to use to create the array of keys, using Object.keys()

const groupsContext = {"01":{"Status":"Active","Name":"Group 1"},"02":{"Status":"Active","Name":"Group 2"}}

let groupKeys = Object.keys(groupsContext)
console.log(groupKeys)

This is the console output:

Array(2897) [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", … ]

I've tried this on codepen and it works so I'm not sure what's different. The only thing I can think of is that I'm missing something between creating the application context and trying to create the keys from the context.

Here is the code I use to create the context:

//Context file

import { useContext, createContext } from "react";

export const GroupsContext = createContext(null);

export function useGroupsContext() {
  return useContext(GroupsContext);
}

//App

import React, { useState, useEffect } from "react";
import { GroupsContext } from "./libs/context/groupsLib";

function App() {
  const [groupsContext, setGroupsContext] = useState(false);

useEffect(() => {
    onLoad();
  }, []);

  async function onLoad() {
    let apiGroups
    try {
      apiGroups = await API.graphql(graphqlOperation(queries.getQuery, { PK: "Status", SK: "Test" }));
      setGroupsContext(apiGroups.data.getQuery.FullGroups)
      
    } catch (e) {
      if (e !== "Error") {
        onError(e);
      }
    }
  }

  return (
      <div>
        <GroupsContext.Provider value={{ groupsContext, setGroupsContext }}>
          <Routing />
        </GroupsContext.Provider>
      </div>
    )
  );
}

export default App;

//getGroups

import { useGroupsContext } from "../../libs/context/groupsLib";

export default function ActiveGroups() {
  const { groupsContext } = useGroupsContext()


let groupKeys = Object.keys(groupsContext)
console.log(groupKeys)

As you can see the array should only have a length of two. How can I create the array to show just the number keys?


Solution

  • Thanks to Nick P for his thoughts on enumerable properties. I've amended the code to this:

    let groupKeys = []
      for (const key in groupsContext) {
        groupKeys.push(`${key}`);
      }
      console.log(groupKeys)