Draity
Draity

Reputation: 394

Show all the data from a nested array of objects in React Native

This is my data in a state called childData: {}

Object {
  "11-5-2019": Object {
    "18:32": Object {
      "color": "Brown",
      "time": "18:32",
    },
    "18:33": Object {
      "color": "Red",
      "time": "18:33",
    },
  },
}

I want to show all this data on one page. I've tried to use a map but it gives me an error. Also I have tried a FlatList.

{this.childData.map(item, index =>
<View key={index}>
    <Text>{item}</Text>
</View>
)}

But I don't know how to get all the data. I want to have the data like this in text:

11-05-2019
  18:32
    brown
    18:32
  18:33
    red
    18:33

Upvotes: 0

Views: 887

Answers (1)

Tim
Tim

Reputation: 10709

The problem is that .map and FlatList are expecting an array. You are passing an object. So first you need to make that you are passing an array.

You can do that by using lodash:

Install lodash with:

npm i --save lodash

and then use it with:

var _ = require('lodash');

Now we can transform your data within the render function :

render() {
   //get all keys, we pass them later 
   const keys = Object.keys(YOUR_DATA_OBJECTS);
   //here we are using lodah to create an array from all the objects
   const newData = _.values(YOUR_DATA_OBJECTS);
    return (
      <View style={styles.container}>
       <FlatList
        data={newData}
        renderItem={({item, index}) => this.renderItem(item, keys[index])}
       />
      </View>
    );
  }

And now we have two helper render functions:

  renderSmallItems(item){
    console.log('small item', item);
    // iterate over objects, create a new View and return the result
    const arr = _.map(item, function(value, key) {
    return (
        <View key={key}>
          <Text> Color:  {value.color} </Text>
          <Text> Time:  {value.time} </Text>
        </View>
    );
  });
     return arr; 
  }
  renderItem(item, key) {
    return(
      <View style={{marginBottom: 15}}>
      <Text> Key: {key} </Text>
      {this.renderSmallItems(item)}
      </View>
    );
  }

Output:

demo image

Working Demo:

https://snack.expo.io/HyBSpYr2E

Upvotes: 2

Related Questions