Home > OS >  React: remove object inside an array
React: remove object inside an array

Time:08-24

I have the following structure assembled inside a state (data, setData):

[
  {
    4b080412-b22c-40fe-a67e-510f96d50063:{
      id: 1231,
      name: "Anna",
      department: "Business"
    }
  },
  {
    8d319764-a49e-4465-a166-a701a5cc2b77:{
      id: 456,
      name: "Tony",
      department: "Marketing"
    }
  },
  {
    23ea617b-210e-4329-9ab1-ecd2afa12e4d:{
      id: 99,
      name: "Francis",
      department: "Sales"
    }
  },
]

I put an 'onClick' on the button passing an 'ID' (eg: '23ea617b-210e-4329-9ab1-ecd2afa12e4d').

But I am not able to delete the related ID. I tried the following ways, but without success:

  const handleClick = (identifier: string) => {        
    setData(
      data.filter((el: any) => {
        if (el[identifier] !== undefined) return el[identifier].product !== id;
      }),
    );

also:

  const handleClick = (identifier: string) => {        
    delete data[identifier]
  );

Can anyone help me how can I access this ID?

CodePudding user response:

Please try this code, it works for me.

setData(data.filter(el => el[identifier] === undefined))

CodePudding user response:

Try running this one:

const handleClick = (identifier: string) => {
  setData(
    data.filter((obj) => {
      return Object.keys(obj)[0] !== identifier;
    }),
  );
};

CodePudding user response:

hi Nosredna I have gone through the approach u have used, and have some logical issues

you can try it like this

const handleClick = (identifier: string) => {        
     const newArr=data.filter(el=>!el[identifier])
     setData(newArr);
};

CodePudding user response:

You can use the filter method if you are passing if on click:

const handleClick = (identifier: string) => {        
    setData(
data.filter((el: any) => {
        // el is an object and if there will be only one key
        // that is the 'ID'
        if (Object.keys(el)[0] !== identifier) return el;
      }),
)
})

Or,

const handleClick = (identifier: string) => {        
    setData(
data.filter((el: any) => {
        // el is an object and if there will be only one key
        // that is the 'ID'
        if (!el.hasOwnProperty(identifier)) return el;
      }),
)
})

If you want to delete, it from the existing array use splice:

const index = data.findIndex((el, index) =>  Object.keys(el)[0] === identifier });
data.splice(index, 1); // but it is expensive operation 
  • Related