Home > Back-end >  If array includes a cetain key then delete entire object using JS
If array includes a cetain key then delete entire object using JS

Time:02-18

I am getting back a 2d array and sometimes I will get an "error" and "message" back for that particular object. The problem I keep running into, Is that the messaging I am getting back varies...How do I go about if the "error" key is mentioned then delete the object entirely.

My Array:

let filtData = [
  [
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "es",
        },
      },
    },
    {
      error: {},
      message: "Cannot read property 'attrs' of undefined"
    },
  ],
  [
    {
      descriptions: {
        attrs: {
          lang: "sp",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "it",
        },
      },
    },
  ],
  [
    {
      descriptions: {
        attrs: {
          lang: "en",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "uk",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
  ],
];

Js Filter - This only works when I know the messaging

let objectToBeRemove = [{ error: {}, message: "Cannot read property 'attrs' of undefined" }];
filtData = filtData.filter((obj) => objectToBeRemove.some((objToRemove) => JSON.stringify(objToRemove) !== JSON.stringify(obj)));

CodePudding user response:

Check that .every of the elements in the subarray lack an error property.

const input=[[{descriptions:{attrs:{lang:"en-GB"}}},{descriptions:{attrs:{lang:"es"}}},{error:{},message:"Cannot read property 'attrs' of undefined"}],[{descriptions:{attrs:{lang:"sp"}}},{descriptions:{attrs:{lang:"en-GB"}}},{descriptions:{attrs:{lang:"it"}}}],[{descriptions:{attrs:{lang:"en"}}},{descriptions:{attrs:{lang:"uk"}}},{descriptions:{attrs:{lang:"en-GB"}}}]];

const filtered = input.filter(
  subarr => subarr.every(obj => !obj.hasOwnProperty('error'))
);
console.log(filtered);

  • Related