Retrieve the value of a nested object within an object, which is located inside an array

I am trying to retrieve the last "message" from each object in my data, but I am unsure of how to accomplish this. Here is a snippet of the data:

{
  data: {
    contacts: [
      {
        name: 'Michele',
        avatar: '_1',
        visible: true,
        messages: [
          {
            date: '10/01/2020 15:30:55',
            message: 'Hai portato a spasso il cane?',
            status: 'sent'
          },
          {
            date: '10/01/2020 15:50:00',
            message: 'Ricordati di stendere i panni',
            status: 'sent'
          },
          {
            date: '10/01/2020 16:15:22',
            message: 'Tutto fatto!',
            status: 'received'
          }
        ],
      },
      {
        name: 'Fabio',
        avatar: '_2',
        visible: true,
        messages: [
          {
            date: '20/03/2020 16:30:00',
            message: 'Ciao come stai?',
            status: 'sent'
          },
          {
            date: '20/03/2020 16:30:55',
            message: 'Bene grazie! Stasera ci vediamo?',
            status: 'received'
          },
          {
            date: '20/03/2020 16:35:00',
            message: 'Mi piacerebbe ma devo andare a fare la spesa.',
            status: 'sent'
          }
        ],
      }
    ]
  }
}

I am looking to extract the last message from each conversation, such as 'Tutto fatto!'

This is what I have so far:

<div v-for="(item, index) in contacts" class="col-12 d-flex justify-content-between align-items-center py-3 px-3">
    <div class="d-flex"> <img class="profile-pic me-3" :src="'img/avatar' + item.avatar + '.jpg'" alt="userpic">
        <div>
            <div class="fw-bold">{{item.name}}</div>
            <p class="text-secondary"> Last message sent</p>
        </div>
    </div>
    <div class="text-secondary mb-5">12:00</div>
</div>

Answer №1

Retrieve the last element from an array using ES2022 Array.at(-1) method.

Check out this working demonstration:

const obj = {
  data: {
    contacts: [
      {
        name: 'Michele',
        avatar: '_1',
        visible: true,
        messages: [
          {
            date: '10/01/2020 15:30:55',
            message: 'Hai portato a spasso il cane?',
            status: 'sent'
          },
          {
            date: '10/01/2020 15:50:00',
            message: 'Ricordati di stendere i panni',
            status: 'sent'
          },
          {
            date: '10/01/2020 16:15:22',
            message: 'Tutto fatto!',
            status: 'received'
          }
        ],
      },
      {
        name: 'Fabio',
        avatar: '_2',
        visible: true,
        messages: [
          {
            date: '20/03/2020 16:30:00',
            message: 'Ciao come stai?',
            status: 'sent'
          },
          {
            date: '20/03/2020 16:30:55',
            message: 'Bene grazie! Stasera ci vediamo?',
            status: 'received'
          },
          {
            date: '20/03/2020 16:35:00',
            message: 'Mi piacerebbe ma devo andare a fare la spesa.',
            status: 'sent'
          }
        ],
      }
    ]
  }
};

const res = obj.data.contacts.map((obj) => obj.messages.at(-1).message);

console.log(res);

Answer №2

If you follow this code snippet, you may gain access:

data.contacts.forEach(user => {
   user.messages[user.messages.length-1].message
   // The first iteration will give you "Tutto fatto!" and in the second one "Mi piacerebbe ma devo    
   // andare a fare la spesa"
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`Utilizing lightgallery.js in combination with Vue 3: A comprehensive guide`

I'm encountering a 500 [vite-node] [ERR_MODULE_NOT_FOUND] error related to 'lightgallery/vue' module. Can anyone provide guidance on resolving this issue? I am currently working with Nuxt version v3.0.0-rc.12 and Vue version v3.2.41 <scr ...

Warning happens two times upon performing a right-click

I've got some code that checks the mouse's position, and triggers an alert followed by a redirect if a certain condition is met. It functions correctly, however, I noticed that if you right-click in one area and then left-click in another area t ...

angular5: The ngFor directive will only function properly after the second button click

Here is my current situation: 1) When the user inputs a keyword in a text field and clicks on the search icon, it triggers an HTTP request to retrieve the data. 2) The retrieved data is then rendered in HTML using ngFor. The issue I am facing is that up ...

Exploring Vue and Nuxt JS: What Causes the Issue of Unable to Create the Property 'display' on the String 'bottom:30px;right:30px;'

this piece of code is designed for a component that allows users to jump back to the top of the page. However, after refreshing the page, it stops working and throws an error. The project uses the Nuxt and Vue framework. Can anyone identify the reason behi ...

Eliminating an element from an array without the need for iteration

I've been reviewing some documentation, but I have a hunch that there may be a simpler way to eliminate one element from an array without having to utilize an iteration loop. http://jsfiddle.net/G97bt/1/ Check out the updated jsFiddle example: http: ...

Managing global HTTP response errors on Vue/axios using Vuex

I've encountered an issue in my VueJS SPA where a strange limbo state occurs. The application fails to recognize that the JWT token has expired, leading it to still display as if the user is logged in. This typically happens after periods of hibernati ...

If one checkbox is selected, the user will be redirected to location.html. If two checkboxes are selected, the user will be

I am facing an issue with designing a form using HTML and JavaScript. My requirement is to include multiple checkboxes in the form. If one checkbox is selected, upon submission, the user should be directed to a specific URL. If two checkboxes are checke ...

Error: Missing responseText in Jquery

Struggling with accessing ajax response data? I have encountered an issue with my ajax request that sends Json to a server and the response returns Json as well. Even though I receive the response, I am unable to access the responseText. Below is the code ...

Steps to create a scrollable container within a div that occupies the entire available space within the div

One of the sections in my div is a scrollable list that needs to adjust its size dynamically based on the screen size. I am struggling with finding a solution that allows the scrollable area to occupy all the remaining space of the parent without specifyi ...

Develop a custom class for importing pipes in Angular 4

Currently, I am working on creating a pipe that will replace specific keywords with the correct strings. To keep this pipe well-structured, I have decided to store my keywords and strings in another file. Below is the code snippet for reference: import { ...

Using the fieldset element in AngularJS Material causes disruptions in my flex layout

My current issue can be illustrated through two code examples: The first example functions properly when the fieldset is not included. In the second example, including the fieldset causes the layout to extend beyond the window when there is long text (in ...

Managing browser back button functionality

I've been struggling to find a solution for handling the browser back button event. I would like to prompt the user with a "confirm box" if they click on the browser back button. If they choose 'ok', I need to allow the back button action, ...

Is it possible to customize the MUI CSS for a specific menu item using the sx prop?

How can I apply the MenuItemStyle to the sx prop of a MenuItem using: const MenuItemStyle = { '&:hover': { backgroundColor: `${theme.color.secondaryHover}`, }, '&:selected, &:selected:hover': { backgroundColor: ...

The addClass() method seems to be malfunctioning following an ajax request

My current project involves setting up an AJAX call that is triggered when a user clicks on an anchor link. Once the AJAX operation is successful, I want to dynamically add a class to the specific anchor that initiated the call. The script itself seems to ...

Displaying a JSON array response on an HTML page with JavaScript and jQuery

After receiving a JSON response with data in array format, I need to display that data on an HTML page. In my HTML structure, I have div elements for merchant name, product name, and a remove button. The JSON data consists of arrays containing the same pro ...

Having trouble deploying my Express/Next app on Netlify

I am facing issues deploying my Next/Express app on Netlify. While the app functions perfectly locally, I encounter problems when attempting to deploy it using Netlify lambda function. Here are the links to my test git repositories: https://github.com/La ...

A React component making a GET request with a delay of one or more clicks

Trying to explain this may be a bit tricky, but essentially, when a user clicks on a component, I trigger a GET request to fetch data for another component. However, this request is only made after a few clicks. I must admit, I'm not entirely sure if ...

Utilizing variable values in HTML and CSS to enhance a website's functionality

My current project involves modifying an HTML web resource for use in Dynamics 365. I need to replace a static URL with a dynamic value obtained via Javascript, specifically: var URL = Xrm.Page.context.getClientUrl(); There are multiple instances within ...

Ways to create a scrollable div with the help of Javascript

I am currently developing a web app on the Tizen platform. Within my HTML5 code, I have a div element with an image set as its background. In certain scenarios, I need to display random text within this div multiple times. The text can vary in size and ma ...

Executing an xajax/ javascript function simultaneously

Is there a way to simultaneously execute the same function? Here is an example: function convert_points() { show_loading(); xajax_ConvertPoints(); xajax_GetRegularGamingCards(); } When xajax_ConvertPoints is called, there seems to be a mill ...