0
votes

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? - sinawic
No this was a mistake when I wrote the question, it's correct in the code. - asker

2 Answers

1
votes

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
 }
})
0
votes
arr => arr && arr[0] ? object.keys(arr[0]) : [];

make sure all items in array have same keys