Home > Back-end >  Remove an array value from within an array of objects
Remove an array value from within an array of objects

Time:09-22

I have an array that looks like this:

const updatedUsersInfo = [
  {
    alias: 'ba',
    userId: '0058V00000DYOqsQAH',
    username: '[email protected]',
    permissionSets: [
      'X00e8V000000iE48QAE',
      'SCBanquetAccess',
      'SCViewOnlyPermission'
    ]
  },
  {
    alias: 'cs',
    userId: '0058V00000DYOqtQAH',
    username: '[email protected]',
    permissionSets: [ 'X00e8V000000iE45QAE', 'SCCorpAdmin', 'SEAdmin' ]
  }
]

I need to remove from the embedded permissionSets array just the value that starts with 'X00' and looks like this after.

const updatedUsersInfo = [
  {
    alias: 'ba',
    userId: '0058V00000DYOqsQAH',
    username: '[email protected]',
    permissionSets: [
      'SCBanquetAccess',
      'SCViewOnlyPermission'
    ]
  },
  {
    alias: 'cs',
    userId: '0058V00000DYOqtQAH',
    username: '[email protected]',
    permissionSets: [ 'SCCorpAdmin', 'SEAdmin' ]
  }
]

I have tried many ways to achieve this, however, no matter which way I do it I get a variable 'undefined'

Here is some of the ways I have attempted this:

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 have also tried to splice but it also returned an error stating the array could not be spliced. I am primarily a C# developer and typescript is an entirely new ball field for me so any help would be great!

CodePudding user response:

You should use map() and filter() to treat the object as immutable (i.e. a data object should not be changed after its creation).

You should not use includes("X00") as it will also match strings like beforeX00after but you only want to remove those starting with X00. Use startsWith("X00") instead.

const updatedUsersInfo = [
  {
    alias: "ba",
    userId: "0058V00000DYOqsQAH",
    username: "[email protected]",
    permissionSets: [
      "X00e8V000000iE48QAE",
      "SCBanquetAccess",
      "SCViewOnlyPermission",
    ],
  },
  {
    alias: "cs",
    userId: "0058V00000DYOqtQAH",
    username: "[email protected]",
    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 implementation uses the spread syntax introduced with ES6 as well as rest properties to create new objects from existing object while updating a property.

  • Related