0

I have a JSON array of objects, I want to create a dynamic table columns/headers based on it in React.

The data:

example = [
  {
    id: 0,
    city: 'New York',
  },
  {
    id: 1,
    city: 'Paris',
  },
]

I want to iterate through the array, get the key and add extra fields. So far I have:

columns() {
    return Object.keys(Example[0]).map((key) => {
      return {
        cityName: key,
        capital: false,
      };
    });
  }

I get the keys, but they are unordered (random) and the extra field is added to all the objects. I want to get each key to use it as table header (column name) and be able to change capital for each object. How can I do that in React?

2
  • are you sure about Example[0]).map((key)... must be with small e? Commented Sep 4, 2018 at 7:52
  • No this was a mistake when I wrote the question, it's correct in the code. Commented Sep 4, 2018 at 7:57

2 Answers 2

1

You can use Array.map for this.

example = [
  {
    id: 0,
    city: 'New York',
  },
  {
    id: 1,
    city: 'Paris',
  },
];
example.map((obj) => {
  return {
   CITY : obj.city,
   ID : obj.id
   // Do whatever with the objects
 }
})
Sign up to request clarification or add additional context in comments.

5 Comments

That returns the field, e.g. 'New York', I want to get the key; city. I want to use the key as table header.
If you want to get the key, now run a loop on objects inside map. i.e. Object.keys on each object and you can easily get the key.
you mean a new map inside map? I'm not sure if that's the best way, or even if it works.
No, object.keys...loop through the obj
example.map((obj) => { for(var k in obj) { console.log(k) // do something with the keys }; })
0
arr => arr && arr[0] ? object.keys(arr[0]) : [];

make sure all items in array have same keys

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.