Skip to content
Advertisement

How to Map objects inside an array – Javascript

This is for a React Native Chat app.

My data should be something like this:

const data = [
 {
   id: 1,
   name: John Doe,
   messages: [
     {text: 'Hello', sentAt: 'time here'},
     {text: 'How are you?', sentAt: 'time here'},
     {text: 'Can we meet?', sentAt: 'time here'}
   ]
   image: { uri: "https://randomuser.me/api/portraits/med/men/97.jpg" },
 },
 {
   id: 1,
   name: Robert Smith,
   messages: [
     {text: 'Hi', sentAt: 'time here'},
     {text: 'Can I call now?', sentAt: 'time here'},
   ]
   image: { uri: "https://randomuser.me/api/portraits/med/men/97.jpg" },
 },
 {
   id: 1,
   name: Roy Pinkham,
   messages: [
     {text: 'Please give me a call', sentAt: 'time here'},
   ]
   image: { uri: "https://randomuser.me/api/portraits/med/men/97.jpg" },
 }
]

I am listing the Chat list using a FlatList:

<FlatList
        data={data}
        keyExtractor={(message) => message.id.toString()}
        renderItem={({ item }) => (
          <MessageItem
            name={item.name}
            message={item.messages.map((message) => message.text)}
            image={item.image}
            read={item.read} // Hard-coded value in data array
            time={item.time} // hard-coded value in data array
            renderRightActions={() => (
              <MessageDelete onPress={() => deleteMessage(item)} />
            )}
            onPress={() => navigation.navigate("Chats", item)}
          />
        )}
        ListHeaderComponent={
          showSearch && <Search query="" onSearchChange={onSearchChange} />
        }
      />

The messages shows like this all stacked up and I am not what is the workaround. What I am trying to achieve is displaying the last message based on timestamp.

enter image description here

Advertisement

Answer

To get the last message of the messages array, set the message attribute of the MessageItem element to the last message, like so:

message={item.messages[item.messages.length - 1].text}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement