The following offset values within the array

Currently, I am trying to extract an array of elements using the following code:

const result = payload.map(({QUALITY, TEMPERATURE, SENSOR_READING_DATETIME, SOURCE_COMPONENT_ID, SENSOR_NAME, NEXT_OFFSET})=> ({
        TELEMATICS: {
          QUALITY,
          TEMPERATURE
        },
      SOURCE_COMPONENT_ID,
      SENSOR_NAME,
      SENSOR_READING_DATETIME,
      NEXT_OFFSET
    }));

The resulting output looks like this:

{
    data: [
            {
                "TELEMATICS": {
                    "QUALITY": 91.98,
                    "TEMPERATURE": 20.5
                },
                "id": 118,
                "SENSOR_READING_DATETIME": "2021-09-24T04:53:06.801Z",
                "SOURCE_COMPONENT_ID": 1,
                "SENSOR_NAME": "TD2",
                "NEXT_OFFSET": 119
            }
            ,
            {
                "TELEMATICS": {
                    "QUALITY": 91.98,
                    "TEMPERATURE": 20.5
                },
                "id": 119,
                "SENSOR_READING_DATETIME": "2021-09-24T05:53:09.774Z",
                "SOURCE_COMPONENT_ID": 1,
                "SENSOR_NAME": "TD2",
                "NEXT_OFFSET": 120
            }
           ]
    }

However, my goal is to extract the NEXT_OFFSET value outside the elements and have it only for the last record in the array.

I would like the output to resemble the example below:

{
    data: [
            {
                "TELEMATICS": {
                    "QUALITY": 91.98,
                    "TEMPERATURE": 20.5
                },
                "id": 118,
                "SENSOR_READING_DATETIME": "2021-09-24T04:53:06.801Z",
                "SOURCE_COMPONENT_ID": 1,
                "SENSOR_NAME": "TD2"
            }
            ,
            {
                "TELEMATICS": {
                    "QUALITY": 91.98,
                    "TEMPERATURE": 20.5
                },
                "id": 119,
                "SENSOR_READING_DATETIME": "2021-09-24T05:53:09.774Z",
                "SOURCE_COMPONENT_ID": 1,
                "SENSOR_NAME": "TD2"
            }
           ],
        "NEXT_OFFSET": 120
}

Could anyone guide me on how to achieve this desired outcome?

Answer №1

If you want to accumulate results and add an extra field when reaching the last item, consider using Array.reduce. Setting the initial value of the extra property as null can handle the 'no results' case as well.

A more straightforward approach would be:

const payload = [
  { a: 1, b: 2 },
  { a: 5, b: 6 },
  { a: 10, b: 11 }
];

const res = payload.reduce(
  (acc, { a, b }, index) =>
    index === payload.length - 1
      ? { ...acc, data: [...acc.data, a],b }
      : { ...acc, data: [...acc.data, a] },

  { data: [], b:null }
);

console.log(res);

In a scenario where you fetch batches of items in certain counts, such as REQUEST_COUNT (e.g., 2000), you could implement it like this:

const res = payload.reduce(
  (acc, { NEXT_OFFSET, ...item }, index) => {
    const data = [...acc.data, item];
    if (index < payload.length - 1) {
      return { data };
    } else {
      const nextOffset =
        payload.length < REQUEST_COUNT
          ? { NEXT_OFFSET: null }
          : { NEXT_OFFSET 
       return {data, ...nextOffset}
    }
  },
  { data: [], NEXT_OFFSET: null }
);

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

What is the best way to assign a class to the parent element when the child element contains a specific class?

Here is the scenario: body { padding-left: 350px; } <body> <div>child</div> </body> Occasionally, the child within body can be different: <body> <div class="service-error">child</div> </body> I ...

Error-free ngClick doesn't trigger AngularJS controller method

I am struggling to trigger the removePlayer(playerId) method upon clicking a button. However, it seems that the method is not being called, as I have placed a console.log() statement at the top and the console remains empty. This situation has left me puz ...

How can I create numerous HTML containers using Javascript?

I've been learning from this tutorial: Instead of just displaying the last database object, I want to display all of them. I have tried outputting the database contents and it's working fine. Now, I just need to adjust the HTML. I attempted to ...

Retrieving information from MongoDB within a specific time range, between a designated start date

Currently, my Mongo database contains JSON data structured like this: { "uSN": "100030001", "timestamp": 1470009600, "timetag": 1082016, "monthtag": 82016, "hourtag": 11, "mintag": 10, "yeartag": 2016, "id": "d100030001_0 ...

Using jQuery to create clickable images by enclosing them in an `<a>` tag

How can I make each image with a specific class clickable? I would like jQuery to: Retrieve the src attribute of the image. Enclose the image within an a href tag that includes that src URL. .clickable { padding: 20px; border: 1px ...

Pattern without anything to duplicate

Could someone help me figure out what I'm doing wrong with this regular expression? I need to create a regex that matches phone numbers in three specific formats: "+38 (093) 937-99-92", "093 937 99 92", and "(093) 937 99 92". As I started working on ...

Using JavaScript to capture patterns with regex

Beginning my journey in automation! I am using wdio5, cucumber, and selenium framework with gherkin language. My task is to create a step file in JavaScript for a gherkin feature that includes these examples: Examples 52.27 .27 2.27 I hope I phrased my ...

Having trouble unselecting the previous item when selecting a new item in Reactjs

I have a list of items and I want to change the background color of the currently selected item only. The previously selected item should deselect. However, at the moment, all items are changing when I click on each one. Can anyone help me solve this issue ...

Employing a dynamic query approach to implement pagination in Spring MVC

In my current Spring MVC project, I am tackling the challenge of implementing pagination for a Review entity which includes fields such as reviewStatus and submission date. While exploring the use of JpaRepository for this purpose, I encountered a roadblo ...

Calling the `firstValueFrom()` method in RxJS will keep the observable alive and not

Hey there, I'm currently having issues with using firstValueFrom(), lastValueForm(), and Observable.pipe(take(1)) in my TypeScript code with Angular 14 and RxJs 7.8.0. I am working with a Firebase server that provides stored image URLs via an API wit ...

Tips for effortlessly adding a JSON object to a table

Let's imagine we have a table structured like this: id| name | family ---+------+--------- 1 | iman | marashi 2 | mike | ... 3 | john | ... 4 | | Now, we also have a JSON object that we want to add to the table: {"name ":"will","family":" ...

Continuously encountering an unhandled syntax error: identifier not as expected

This excerpt is from my app.js file for a mini express app I'm working on. var loginPost = function() user = { username: $('#username').val(), password: $('#password').val(), }; $.ajax({ url ...

Unlock the power of WebVR in your WebView using krpano!

After successfully running krpano with WebVR on Chrome and Firefox, I encountered an issue where the cardboard button was not visible or enabled when embedded in a WebView on Android. However, to my surprise, the compiled apk with the WebView showed the ca ...

Having trouble with BOM issue while reading a .json file?

I need to edit a specific field in a .json file while the program is running. The issue arises when attempting to read the file: JSONObject jOb=null; try { jOb = new JSONObject(filePath); } catch (JSONException e) { ...

Forward to a SubDomain

Utilizing Yellowtree's GEOIP-Detect plugin, I attempted to implement a location-based redirection system for visitors. Unfortunately, I encountered issues with the code execution. The process initially involves extracting the user's IP address an ...

Is there a method to redirect and display a JavaScript message efficiently?

Once the user has updated a record, I want to automatically redirect them to another page where they will be notified with a JavaScript message (alertify.notify()) confirming that the update was successful. I am unsure if it's possible to dynamically ...

Failed to access element from the array using specified id

Seeking assistance with creating dynamic pages for each object in the boxArray file. I've developed a service called boxService to extract objects. While I am able to retrieve all elements successfully, encountering errors when attempting to extract i ...

Append a new object of a class to a collection

Within my codebase, I've defined a class called Email within a class library to store values collected from textboxes in the UI. The snippet of code is structured as follows: namespace MessageLibrary { public class Email { private int ...

JavaScript forEach: alter items

I am facing an issue with using the forEach method on an array. Despite it being a mutator, it is not mutating the values in the original array as expected. Can anyone help me figure out what could be causing this problem? let array = [1, 2, 3, 4]; //de ...

Troubleshooting problems with loading data while implementing an iOS infinite scroll feature in Ionic 3

Within my application, there exists a chat feature in which additional messages are loaded as the user scrolls up. I have implemented Ionic's default "infinite scroll" component with a position of 'top' in order to detect when the user reach ...