Is there a way in Typescript to filter for the first instance of a unique object in an array of objects?

Having an array of JSON objects like this, the task is to iterate through it and retrieve the first occurrence of 'appname', such as 'app1' or 'app2', and store the entire object for each...

 myArray[
        {
            "myApp": {
                "appname": "app1",
                "servername": "randomname-xyx",
                "status": "DOWN"
            }
        },
        {
            "myApp": {
                "appname": "app1",
                "servername": "another-random-name",
                "status": "DOWN"
            }
        },
        {
            "myApp": {
                "appname": "app2",
                "servername": "some-server",
                "status": "UP"
            }
        },
        {
            "myApp": {
                "appname": "app2",
                "servername": "abc-server",
                "status": "DOWN"
            }
        },
        {
            "myApp": {
                "appname": "app2",
                "servername": "qwerty-srv",
                "status": "DOWN"
            }
        },
        {
            "myApp": {
                "appname": "app2",
                "servername": "last-server",
                "status": "UP"
            }
        },
    ]
  

Presently using this code snippet...

this.getAppClient.getFullList()
        .subscribe((apps) => {
            this.applicationList = [...new Map(apps.myArray.map((o: { myApp: { appname: any; }; })=>[o.myApp.appname, o])).values()]
        })
      

...the filter is currently returning the last object instead of the first one for each 'appname'. The output looks like this...

{
            "myApp": {
                "appname": "app1",
                "servername": "another-random-name",
                "status": "DOWN"
            }
        },
    {
            "myApp": {
                "appname": "app2",
                "servername": "last-server",
                "status": "UP"
            }
        },
    

However, the expected output should look like this...

{
            "myApp": {
                "appname": "app1",
                "servername": "randomname-xyx",
                "status": "DOWN"
            }
        },
    {
            "myApp": {
                "appname": "app2",
                "servername": "some-server",
                "status": "UP"
            }
        }
    

Is there a way to adjust the filtering logic to achieve the desired outcome?

Answer №1

Try this out

const appList = new Set<string>();
const resultList: any[] = [];
myArray.forEach(element => {
  if(!appList.has(element.app.appname)) {
    appList.add(element.app.appname);
    resultList.push(element);
  }
})
console.log(resultList);

Here is the output:

[{
  "app": {
    "appname": "app1",
    "servername": "randomname-xyx",
    "status": "DOWN"
  }
}, {
  "app": {
    "appname": "app2",
    "servername": "some-server",
    "status": "UP"
  }
}] 

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

It seems like there is an issue with your network connection. Please try again

Recently, I made the switch to EndeavourOS, which is based on Archlinux. I completed all my installations without any issues and attempted to create a new NestJs project after installing NVM, Node's latest version, and the NestJs/cli. However, when I ...

My current issue lies in my ability to successfully retrieve data from the controller using AJAX calls in .NET CORE, however, I am

Trying to pass a string id from the View to the controller for calculations and then return a string back to the view. Although I can receive the return data from the controller, the parameter 'String data' in the action is always null, indicatin ...

Is there a way to retrieve the type of a generic class in JavaScript?

class Alpha { static construct<T extends typeof Alpha>(this: T): InstanceType<T> { const v = new Alpha(); return v as InstanceType<T>; } } class Beta extends Alpha {} const x = Alpha.construct(); // generates Alpha const y = ...

Node: How can I retrieve the value of a JSON key that contains a filename with a dot in

I have a JSON file named myjson.json, with the following structure: { "main.css": "main-4zgjrhtr.css", "main.js": "main-76gfhdgsj.js" "normalkey" : "somevalue" } The purpose is to link revision builds to their original filenames. Now I need to acce ...

Tips for formatting result data when using FullCalendar's eventSources URL

I am looking to retrieve my event data for fullcalendar from a separate URL. I have been following the method mentioned here: https://fullcalendar.io/docs/eventSources $('#calendar').fullCalendar({ eventSources: [ '/feed1.php' ...

Upgrade your angular/ionic app by swapping out inline data with a JSON service!

Could you assist in updating the current service with json data? The service currently has hardcoded information, and the corresponding controller is provided below. services.js angular.module('directory.services', []) .factory('Employe ...

Make sure that 'RegisterAPI' has a designated 'serializer_class' attribute, or if not, make sure to customize the 'get_serializer_class()' method

I am currently facing an issue while trying to display a register view. Despite making modifications to the views file, I am still encountering errors and unsure about how to resolve them. Below is the content of my views.py file: from django.shortcuts imp ...

What is the reason that Jest is not able to spy on the function?

A custom Hook was developed with only one function being imported. Ensuring this function is called with the correct arguments is crucial. import { IsValueAlreadyRegistered } from "../../entities/registration/actions"; export const useForgetPass ...

Is there a foolproof way to generate JSON data using PHP?

I am new to JSON and I have XML results that I want to convert to JSON format. The data is retrieved from a mySQL array. My issue arises when dealing with multiple nodes with the same name in the XML result, as shown below: <results> <result ...

What is the best way to eliminate a flowfile or entire object containing a null field utilizing JoltTransformJson in Apache NiFi?

Is there a way to remove flowfiles if the value of a specific field is null using JoltTransformJson processor in NiFi? Below is an example of the data: emp.json: [ { "Name" : "john Smith", "DOB" : "2000-07-14& ...

What is the process for converting a string literal into raw JSON and then storing it?

When trying to edit object values using a text input element and JSON.stringify(txt, null, 2), everything seems fine initially. However, after submitting the input, I end up with unwanted characters like "/n" and "\" within the string literal. Despite ...

When a 404 error is thrown in the route handlers of a Next.js app, it fails to display the corresponding 404 page

I am encountering an issue with my route handler in Next.js: export async function GET(_: Request, { params: { statusId } }: Params) { const tweetResponse = await queryClient< Tweet & Pick<User, "name" | "userImage" | &q ...

Deciphering a JSON code containing a nested JSON string in ExtJS4

Looking to decode a JSON string within a JSON string using Ext.decode(string) in extjs4, similar to the example below: var string = "{success:true, rows:[{"jsonfields":"[ {\\"name\\":\\"cm:title\\",\\"tit ...

Customized Grafana dashboard with scripted elements

I'm running into an issue while using grafana with graphite data. When I attempt to parse the data, I encounter an error due to the server not providing a JSON response. I am experimenting with scripted dashboards and utilizing the script found here: ...

RxJS: Transforming an Observable array prior to subscribing

I am retrieving data (students through getStudents()) from an API that returns an Observable. Within this result, I need to obtain data from two different tables and merge the information. Below are my simplified interfaces: export interface student Stude ...

The pairing of Transpiller and Internet Explorer 8 is like a dynamic

In starting my new project, I am considering using BabelJS. However, there is a significant requirement that must be met: it needs to be compatible with IE8. ISSUE: Babel compiles ES6 to ES5, but the support for ES5 on IE8 is lacking. Are there any alter ...

Combining Two JSON Arrays Featuring Unique Keys

I have two JSON arrays with slightly different keys. The first JSON array contains the keys id, name, and title. The second JSON array includes id, title, forename, name, and company. I am wondering if it's possible to merge these two arrays so th ...

Basic jQuery request for JSON data

In an effort to send user data to a PHP script and display the results in an element, I am utilizing JSON. The process works smoothly until reaching the response stage. Despite receiving the correct results when logging to the console, attempting to append ...

What could be the reason for the error message (JSON ERROR: no value for)?

I have been working on a Kotlin code to fetch data for a dictionary app using JSON Request Object. The call seems to be successful as I can see the website receiving the data, but I'm encountering an issue where the results object is not being populat ...

Discovering the most efficient route between two locations within a grid of values

I'm currently working on a game where I need to find the shortest route between two points. https://i.sstatic.net/jBnEd.png In my map, I have a 2D array called matrix: Node[][], class Node{ index: { x: number, y: number }, isAvai ...