3

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.