Take out a specific element from an array consisting of multiple objects

I have a specific array structure and I need to remove elements that match a certain criteria. Here is the initial array:

const updatedUsersInfo = [
  {
    alias: 'ba',
    userId: '0058V00000DYOqsQAH',
    username: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8bab998bcb6b9e8edf6bbb7b5">[email protected]</a>',
    permissionSets: [
      'X00e8V000000iE48QAE',
      'SCBanquetAccess',
      'SCViewOnlyPermission'
    ]
  },
  {
    alias: 'cs',
    userId: '0058V00000DYOqtQAH',
    username: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32514172565c5302071c515d5f">[email protected]</a>',
    permissionSets: [ 'X00e8V000000iE45QAE', 'SCCorpAdmin', 'SEAdmin' ]
  }
]

The goal is to remove elements from the permissionSets array that start with 'X00'. The updated array should look like this:

const updatedUsersInfo = [
  {
    alias: 'ba',
    userId: '0058V00000DYOqsQAH',
    username: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="086a69486c6669383d266b6765">[email protected]</a>',
    permissionSets: [
      'SCBanquetAccess',
      'SCViewOnlyPermission'
    ]
  },
  {
    alias: 'cs',
    userId: '0058V00000DYOqtQAH',
    username: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f1c0c3f1b111e4f4a511c1012">[email protected]</a>',
    permissionSets: [ 'SCCorpAdmin', 'SEAdmin' ]
  }
]

I have attempted different methods to achieve this, but I keep encountering issues and getting 'undefined' as the result. Here are a couple of the approaches I tried:

let test = updatedUsersInfo.forEach((element => element['permissionSets'].filter((permissionSet) => !permissionSet.includes('X00'))));


let test2 = updatedUsersInfo.forEach(element => {
    element['permissionSets'].filter((permissionSet) => {
      return !permissionSet.includes('X00')
    });
  });

I also attempted to use the splice method, but encountered errors indicating that the array could not be spliced. As a developer primarily experienced in C#, TypeScript presents a new challenge, so any assistance or guidance would be greatly appreciated!

Answer №1

For managing objects immutably, it is recommended to utilize the map() and filter() methods.

Avoid using includes("X00") as it may not match the specific strings required. Instead, prefer startsWith("X00") for more precise results.

const updatedUsersInfo = [
  {
    alias: "ba",
    userId: "0058V00000DYOqsQAH",
    username: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="45272405212b2475706b262a28">[email protected]</a>",
    permissionSets: [
      "X00e8V000000iE48QAE",
      "SCBanquetAccess",
      "SCViewOnlyPermission",
    ],
  },
  {
    alias: "cs",
    userId: "0058V00000DYOqtQAH",
    username: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8be8f8cbefe5eabbbea5e8e4e6">[email protected]</a>",
    permissionSets: ["X00e8V000000iE45QAE", "SCCorpAdmin", "SEAdmin"],
  },
];

const updated = updatedUsersInfo.map((info) => ({
  ...info,
  permissionSets: info.permissionSets.filter((p) => !p.startsWith("X00")),
}));

console.log(JSON.stringify(updated, null, 4))
/* StackOverflow snippet: console should overlap rendered HTML area */
.as-console-wrapper { max-height: 100% !important; top: 0; }

This approach takes advantage of the spread syntax and rest properties in ES6 to efficiently create new objects while updating specific properties.

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

Looking to target and modify specific elements within a MongoDB array using Java

I'm looking to update a specific element in a Mongo array while applying filters. I attempted using BasicDBObject, but I can't utilize filters because my collection is of type MongoCollection. MongoCollection collection = db.getCollection(tnId) ...

Creating Production Files for Web using RxJs and TypeScript

I am interested in developing a JavaScript Library using RxJs (5.0.0-Beta.6) and TypeScript (1.8.10). My TypeScript file is successfully compiling. Below are the files I have: MyLib.ts: /// <reference path="../../typings/globals/es6-shim/index.d.ts" ...

Interpolation is not available for my Angular application

I am having trouble with using interpolation on my input in this code. I tried setting the value of the input to be the same as the User's username, but it doesn't seem to work. <ion-header> <ion-toolbar> <ion-buttons slot=&q ...

Testing a click event in Angular that triggers only the navigateByUrl function, utilizing Jasmin and Karma

Need help writing unit test cases for click events in Angular using Jasmine & Karma onClickCancel(): any { this.router.navigateByUrl('login'); } Seeking advice on how to write unit tests for click events that open Material dia ...

How can I effectively test static navigationOptions using Jest and Enzyme in a React Navigation and TypeScript environment?

Currently, I am developing a React Native app using TypeScript. For component testing, I rely on Jest and Enzyme. Additionally, I have integrated React Navigation into my project. On one of the screens, the navigationOptions are as follows: static naviga ...

What is the best way to transform a standard array into a record without losing the specific data types in each position?

Imagine type Individual = { name: string; age: number; }; const john = { name: "John", age: 28, } as const; const emily = { name: "Emily", age: 35, } as const; I am looking to create a function that takes an individual an ...

Retrieve the duplicated items from an array by comparing two specific properties in JavaScript

I need assistance in identifying and retrieving duplicate objects within an array that share similarities in 2 specific properties. Consider the object structure below: let arry = [ {Level: "A-1", Status: "approved"}, {Level: &q ...

The typescript compiler encounters an error when processing code that includes a generator function

Recently, I started learning about TypeScript and came across the concept of generators. In order to experiment with them, I decided to test out the following code snippet: function* infiniteSequence() { var i = 0; while(true) { yield i++ ...

Accessing Child Properties in Parent Component using Typescript

New to the world of Typescript! Imagine having a component called TitleSubtitle that consists of both a Title and a Subtitle component. The Title component comes with props: interface TitleProps { text: string; } The Subtitle component also has props ...

The frontend is not triggering the Patch API call

I am having trouble with my http.patch request not being called to the backend. This issue only occurs when I try calling it from the frontend. Oddly enough, when I tested it in Postman, everything worked perfectly. Testing the backend on its own shows t ...

How to effectively utilize TypeScript in a team environment using both Atom and VSCode?

Our team utilizes TypeScript with both Atom and VSCode as our editors, but we are facing challenges with the tsconfig.json file. VSCode is not recognizing the typings, causing the namespace for 'ng' (for Angular 1.x) to be unknown in VSCode. Wh ...

What strategies can be used to enhance the efficiency of comparing two arrays?

I have been exploring ways to compare arrays and determine their similarity. The code snippet I currently have is as follows: float totalSame = 0F, percentSame = 0F, totalElements = 0F, sameness; foreach (va ...

Utilizing dual functions within the onChange event handler in React

I have a situation where I need to pass a function from a parent component to a child component through the onChange event, as well as another function in the child component to update its own state. How can I achieve this? Parent export function Fruits() ...

The function is missing a closing return statement and the return type does not specify 'undefined'

It seems like the function lacks an ending return statement and the return type does not include 'undefined'. In a recent refactoring of the async await function called getMarkets, I noticed that I had mistakenly set the return type as Promise: ...

Run a script in a newly opened tab using the chrome.tabs.create() method

Struggling with executing a script using chrome.tabs.executeScript() in the tab created with chrome.tabs.create()? Despite searching for solutions, nothing seems to be working as expected. Check out my current code below: runContentScript(){ c ...

How can the return type of a function that uses implicit return type resolution in Typescript be displayed using "console.log"?

When examining a function, such as the one below, my curiosity drives me to discover its return type for educational purposes. function exampleFunction(x:number){ if(x < 10){ return x; } return null } ...

The split function in JavaScript is exhibiting some unusual behavior

There is something wrong with my code challenge1 = () => { var data = fs.readFileSync('santa21.txt', 'utf8'); data = data.toString(); dataSplit = data.split(' ') console.log(dataSplit); }; challenge1(); The result of the ...

The specified 'detail' property cannot be found on the given type '{}'. Error code: 2339

I encountered the error mentioned in the title while working on the code below. Any suggestions on how to resolve this issue? Any assistance would be greatly appreciated! import { useHistory } from "react-router-dom"; let h ...

Methods for resolving a ViewStyle typescript issue in react native

Trying to pass a width parameter into StyleSheet is causing an error like this: <View style={styles.children(width)}>{children}</View> Here's how I'm trying to use it: const styles = StyleSheet.create({ modalContent: { flex: ...

What is the most effective method of testing with jest to verify that a TypeScript Enum list contains all the expected string values?

Recently, I created a list of enums: export enum Hobbies { Paint = 'PAINT', Run = 'RUN', Bike = 'BIKE', Dance = 'DANCE' } My goal is to iterate through this list using Jest and verify that all the string ...