What is the best way to retrieve the last item from an array of objects?

Seeking guidance on how to always display the last item from an array called items, which is part of a JSON object received from the server. Would like to know how this can be achieved using AngularJS or native JavaScript.

In this particular scenario, I need to show the text Chief Administrative Officer.

main.js

  angular.forEach($scope.rcsaErhTreeData, function(val) {
      angular.forEach(val, function(val) {
          console.log('this is the array value', val[0].text);
      });
  });

json.js

[{
    "uid": null,
    "index": 0,
    "selected": null,
    "expanded": null,
    "id": 2701,
    "text": "BAC Enterprise Wide",
    "parentId": 0,
    "items": [{
        "uid": null,
        "index": 0,
        "selected": null,
        "expanded": null,
        "id": 4114,
        "text": "Chief Administrative Officer",
        "parentId": 2701,
        "items": []
    }]
}]

Answer №1

Executing the provided code snippet within your environment will yield the expected outcome.

console.log(JSON.stringify(items[items.length - 1]));

In the console, you will see the stringified result...

Appreciatively, Paras

Answer №2

While I may not be well-versed in Angular.js programming, the idea is to achieve the desired outcome in one of two ways: 1. One option is to iterate through a loop and update the variable value with each subsequent value, ensuring that the final value remains unchanged. However, this method is not recommended due to potential performance issues and the unnecessary use of a loop when it can be avoided. Pseudo code:

var outVal='';
angular.forEach($scope.rcsaErhTreeData, function(val) {
      angular.forEach(val, function(val) {
          outVal = val[0].text);
      });
  });
console.log('this is the last item value', outVal);
  1. Alternatively, you could determine the length of the val array and retrieve the value at its last index. Unfortunately, as I'm not an expert in this language, I cannot provide an example code for this approach. My apologies for any inconvenience.

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

Navigate to a refreshed version of the page with varying parameters using React Navigation

Currently, I am utilizing React Navigation for navigating between different pages within my app. One of the pages is the Profile page which displays a user info card along with their posts. Within this Profile component, I have integrated the Post componen ...

I have been working on creating a hangman game, and although I have figured out the logic behind it, I am experiencing an issue where it is not functioning properly. After inspect

I am currently working on a basic hangman game using only HTML and JavaScript. I have the logic in place, but it doesn't seem to be functioning correctly. When I inspected the element, it showed an error saying 'undefined toUppercase.' As a ...

Learn the process of appending an item to a list using Vue.js

Recently starting with vue.js and facing an issue: data: { ws: null, newMsg: '', username: null, usersList: '' }, created: function() { var self = this; this.ws = new We ...

Confusion about the unwinding of the call stack in the Graph Depth-

Issue with function: hasPathDFSBroken Fix implemented in: hasPathDFS The updated version includes a forced parameter to address the issue, which I would prefer to avoid. I'm trying to comprehend why in the broken version, when the call stack unwinds ...

Adding JSON data to an HTML attribute: A step-by-step guide

I need help with appending one of the values from my JSON object to an HTML attribute value. This is what I'm currently trying: <div ng-messages="registrationForm.[contact.id].$error"> In this example, contact.id is coming from a JSON object, ...

Using jQuery, you can create and add an element to the page when a user clicks

Currently, my webpage contains numerous anchor tags that link to various video files, along with a single div element: <a href="http://www.example.com/example-1.mkv" class="video">1</a> <a href="http://www.example.com/example-2.mkv" class=" ...

Guide on creating 3D Shapes using Three.js and Mesh Data

Data Example: Interpretation of the Mesh format(mw/1): { "ID": 6, "frameNumber": 580, "Mesh": [[0.52147865, 0.35447019, -1.05268724], [1.02147865, 0.35447019, -1.05268724], [0.52147865, 0.35447019, -1.05268724], [0 ...

What is the best way to modify the values in an initialized array once the fetchData method has been executed?

As a beginner in Vue.js, I am currently working on a project that involves updating initialized arrays in the data() section of my component using the fetchData method. Below is a simplified version of the code: <script> import axios from 'axi ...

Issues with selected value in ng-options on AngularJS

I've encountered an unusual issue while using ng-options in AngularJS. Here's the basic scenario I'm dealing with: Assign a value to ng-model for the selected option Retrieve the values for the 'select' from a backend source Lin ...

Issue: Module '@discordjs/opus' is not found

My Discord speech recognition code runs successfully but encounters an error as soon as it joins a channel. The error message displayed is: "Error: Cannot find module '@discordjs/opus'". Require stack: - C:\Users\SURYASH\Desktop&bs ...

Guide to testing error throwing in error events with Jest

I am having an issue with a particular learning case. The code snippet below is what I am dealing with and I aim to test error throwing: export const someFunction = async () => { //... const fileReadStream = createReadStream(absoluteFilePath) .on(&a ...

What is the best way to replace a core class from a library with a new

I am currently utilizing an npm library which contains a class called MapRepository with promise methods for fetching data from the server: export class MapRepository { constructor( readonly globalEvents: MapGlobalEvent, baseWebApiUrl: string, ...

Tips for sorting the echarts line chart on a weekly basis using angular

How can I filter the echarts line chart by week in Angular? Currently, it displays all records like 2019-10-27 10:15:00, 2019-10-27 10:15:30, 2019-10-27 10:16:00, 2019-10-27 10:19:00. Instead, it should only show dates like 2019-10-27. For example, if ther ...

"Exploring the process of integrating a controller into an external HTML file using AngularJS

I'm relatively new to AngularJS. In my web app, I have a set of buttons: index.html <button class="aButton">a</button> <button class="bButton">b</button> <script> $(document).ready(function(){ $(".aButton"). ...

The Three.js raycaster fails to intersect with objects once they have been displaced from their original position

I am encountering an issue with the raycaster: When I place an object at the origin (0, 0, 0), the raycaster can detect it. However, if I move the object to a different position, like (0, 300, 0), the raycaster no longer hits the object. I have double-ch ...

Trigger a fire event upon entering a page containing an anchor

My query is similar to this particular one, with slight differences. I am working on a page that includes an anchor, such as page.html#video1. Within this page, there are multiple sections identified by ids like #video1, #video2. Each section comprises of ...

Warning: Attempting to destructure the property 'name' from 'req.body', which is undefined, is causing a TypeError

Currently, I am diving into the world of MERN Stack web development and running into a unique issue. When using Postmate to input data from the body to the database, everything works smoothly when done from the server.js file. However, when attempting the ...

Seamless transitions while deactivating a conditionally displayed component in React

Here is my code snippet from App.js: export const App = () => { const [toggled, setToggled] = useState(false); const [ordering, setOrdering] = useState(false); const handleColorModeClick = () => { setToggled((s) => !s); }; const ha ...

MongoDB Disregarding Query Parameters

Could this be a potential Node.js driver problem, or am I overlooking something? const users = await User.find({ 'test.test': { $gt: 0 } }).lean(); None of my User records include the test object, so none should match the criteria set by this fi ...

Using Angular directive with ng-class to display or hide element

I am trying to implement a feature in my directive template where an element is shown or hidden on mouseenter. Below is the code for my directive: angular.module('myApp') .directive("addToRoutes",['$http', '$timeout', functio ...