How to list out every key value in an object in React?

Viewed 3704

I currently have a data set which is an array of objects. I'm using .map to list out a certain key in each object.

        {
          data.map(graph =>
            <div key={graph.ID}>
              <h2>{graph.name}</h2>
            </div>
          )
        }

graph is a single object within the data. This prints out the name key for each object in the list. The thing I'm having trouble with now is listing out every single key in each object. Some objects in the list have more keys than others so I can't just list out each key manually. Does anyone know how to do that?

1 Answers

What you can do is, use .map() again, but using Object.keys(obj).map():

var graphs = [
  {
    graph: {
      name: "Praveen Kumar",
      age: 27,
      space: "YouTube"
    }
  }, {
    graph: {
      name: "Cat Techie",
      age: 25,
      gender: "Female"
    }
  }
];
console.log(graphs.map(item => {
  return `The value of ${item.graph.name}'s values are:
` + Object.keys(item.graph).map(key => {
    return `- ${key}: ${item.graph[key]}`;
  }).join("\n");
}));

On the console, I get this way:

The value of Praveen Kumar's values are:
- name: Praveen Kumar
- age: 27
- space: YouTube
The value of Cat Techie's values are:
- name: Cat Techie
- age: 25
- gender: Female

The above two objects have different properties: space and gender and you can use Object.keys() to get them and their values. You can also use Object.entries() too.

This is the basic idea. You can implement this one in React too. If you need a React solution, I am happy to provide the same.

Related