1

I have a json from an api response as below:

centres = [{
    id: 1,
    name: "DEF",
    },{
    id: 2,
    name: "ABC",
  }]

Now I want to populate that above data in a FlatList

return(
  <View>
    <FlatList
      data={this.state.centres}
      renderItem={({item}) => <CentreComponent centre={item}/>}
    />
  </View>
);

But I cant do the above as the data (centres) doesnt have a "key" property.

Now I can loop through each item in the array and add a property "key" which has the same value as ID. But I find this in efficient.

Is there a better way to map "id" column to "key" to render the FlatList

Mateen-Hussain
  • 718
  • 1
  • 13
  • 29

2 Answers2

2

The fastes way I can see this happen is by iterating over the array.

const centres = [{
    id: 1,
    name: "DEF",
  },{
    id: 2,
    name: "ABC",
}];

const newCentres = centres.map( ( item ) => ({ key: item.id, name: item.name }) );

console.log( JSON.stringify( newCentres ) )
// [{"key":1,"name":""},{"key":2,"name":""}]
Dominik
  • 6,078
  • 8
  • 37
  • 61
1

Try using keyExtractor . Please update your code as:

return(
 <View>
  <FlatList
   data={this.state.centres}
   keyExtractor={(item, index) => item.id}
   renderItem={({item}) => <CentreComponent centre={item}/>}
  />
  </View>
);
Rohan Kangale
  • 931
  • 4
  • 11
  • 29