Retrieving the final element from a TypeScript JSON array

I am trying to retrieve the value of the "id" property from the last element in an array of JSON objects. While I can easily find each element by id, I specifically need to extract the value of the last "id" in the array of JSON objects. In the example provided below, the desired value is '3'. Appreciate any help in this regard!

let types: any[] =
    [
        {'id': '0', 'value': ''},
        { 'id': '1', 'value': '' },
        { 'id': '2', 'value': '' },
        { 'id': '3', 'value': '' },
    ]; 

let index = 0;
let indexNext = 1;
types.forEach((item) => { 
    if (item.id == index) { 
        item.value = 'Book';
        console.log(item.value); //Book
    }
    if (item.id == indexNext) { 
        item.value = 'Magazine';
        console.log(item.value); //Magazine
    }
})

Answer №1

Grabbing the last element of an array in JavaScript can be done using types[types.length - 1]
.

If you're iterating through each item in an array using forEach, and need to handle the last item differently, you can utilize the index parameter that is passed to the callback function. By writing

types.forEach((item, indexForItem) => { ... });
, you can then compare the indexForItem to types.length - 1 to identify whether it is the last one or not.

Answer №2

Give this a shot:

Retrieve the id of the last element in the types array using JavaScript: types[types.length - 1]['id']

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

To run multiple environments with react-native-dotenv in a React Native project using Typescript, only the local environment is activated

Currently, I am facing an issue while trying to initialize my React Native app with TypeScript in three different environments - development, local, and testing. When I attempt to run APP_ENV=testing expo start or APP_ENV=development expo start, it always ...

Leveraging jq in Jenkins pipeline

Currently, in my scenario, I am executing a pipeline that utilizes the AWS CLI through the withAWS plugin. To extract the necessary data, I employ jq. The issue arises when the sh command returns the output as a String. What is the best method to convert t ...

Trouble arises when trying to import Jest with Typescript due to SyntaxError: Import statement cannot be used outside a module

Whenever I execute Jest tests using Typescript, I encounter a SyntaxError while importing an external TS file from a node_modules library: SyntaxError: Cannot use import statement outside a module I'm positive that there is a configuration missing, b ...

Utilize NestJS to consume EventPattern exclusively when the header variable matches a specific value

I've been working on a NestJS project where I'm using a Kafka server to emit events and NestJS to consume them. My goal is to create a consumer with the topic my-topic that is triggered only when a specific value is present in the header variable ...

Webpack 2.7.0 throws an error: "Unexpected parameter: theme"

At the moment, I am on webpack 1.16.0 and using --theme as an argument to set the output path and plugin paths. The command appears as: rimraf dist && webpack --bail --progress --profile --theme=<name of theme> However, as I try to upgrade ...

What is the appropriate event type to pass to the onKeyPressed function in a React application utilizing MaterialUI and written with Typescript?

I am currently working on a React application using Typescript and MaterialUI, where I have implemented a TextField component. My goal is to capture the value of the input HTML element when the user presses the enter key. To achieve this, I have created ...

Python pymysql encountering a syntax error when trying to insert a JSON object

Encountered the following error when trying to insert data into a SQL database table using Python: pymysql.err.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the ...

Importing configuration file in CRA Typescript with values for post-deployment modifications

I am currently working on a React app that utilizes Create React App and Typescript. My goal is to read in configuration values, such as API URLs. I have a config.json file containing this data, here's a sample snippet with placeholder information: { ...

Issues persist with @typescript-eslint/no-unused-vars not functioning as expected

.eslintrc.json: { "root": true, "ignorePatterns": ["projects/**/*"], "overrides": [ { "files": ["*.ts"], "extends": [ "eslint:recommended", ...

Different techniques to access values in a JSON array without relying on specific index positions

After making a request to an API, I received a JSON array with various attributes. One of the attributes is "State" and my task is to extract all the "EventName"(s) where State: "PR". The user will select the state from a dropdown menu. In order to achiev ...

Encountering difficulties when compiling my Angular application

Currently, I am working with Angular 2. To include Bootstrap in my project, I utilized the node.js command prompt for installation. npm install ngx-bootstrap --save I made adjustments to the .csproj file in order to deploy my application on the server vi ...

Unable to retrieve JSON information

Currently, I am working on implementing a dynamic dropdown list feature in a Laravel project. To achieve this, I have decided to use Jquery and Ajax for the functionality. <script type="text/javascript"> $('#country').on('change&a ...

Replacing HTML text with JSON data can be easily achieved by using JavaScript

After receiving data from an API and converting it into JSON format, I encountered difficulty when attempting to change a selected element in HTML. Every time I tried to do so, I either got 'undefined' or 'Object Object' as the output. ...

Is it possible that an object sent as a response body from a Spring MVC application's controller cannot be fetched using the jQuery AJAX method?

After making an AJAX call, the EmployeeBean object is not being returned and no exception is being thrown. Here is the code snippet from the controller method: I am trying to return an EmployeeBean object from this method using @Responsebody @RequestMapp ...

What is the process of implementing a particular FormControl from a FormArray in my HTML file?

My FormArray initialization code is as follows: this.contents.forEach(content=> { this.formArray.push( new FormControl(content.text, Validators.required)); }); Now, I am trying to associate a specific FormControl with my textarea by using i ...

Leveraging JSON Schema If-Then-Else for Altering Property Data Types

Exploring the amazing capabilities of if-then-else keywords in JSON Schema 07 has been an eye-opening experience for me. I am intrigued by the idea of altering the type of a property based on the response to another property. My goal is to achieve someth ...

Convert the PHP API response into a float number and ensure that it returns as a whole number

When I make a call to an external API, I am able to successfully retrieve the result. However, I am encountering an issue where a numerical value in one specific field is being converted into a float number. Here is how I am handling the API response: pr ...

Error: You can't use the 'await' keyword in this context

I encountered a strange issue while using a CLI that reads the capacitor.config.ts file. Every time the CLI reads the file, it throws a "ReferenceError: await is not defined" error. Interestingly, I faced a similar error with Vite in the past but cannot ...

Using Angular2 and Typescript to declare a variable of type "any" can result

Hello StackOverflow community, I am encountering an issue with my JavaScript code where a global variable is sometimes not defined. I have a configuration class in Angular2 that imports this global variable using 'declare var any'. Within the cl ...

Matching only the specified Records in an array of Typescript generic objects

Check out this demo: https://tsplay.dev/Nnavaw I am working with an array that has the following structure: Array<{ id?: string; text?: string; date?: Date; }> This conflicts with the current implementation: data: Array<Par ...