Home > Software engineering >  How to delete an array inside an array in React JS?
How to delete an array inside an array in React JS?

Time:11-14

Let's say I have (is more data than just id and description but as an example I just added those):

tempArray:
[
  {id:"L-2627", description: "Book1"},
  {id:"L-62961", description: "Book2"},
  {id:"L-70605", description: "Book3"}
]

and when I want to delete something I have to check it and when I check it I get the ID, let's say is the first one L-2627:

enter image description here

if I check all of them then I get all the ids

enter image description here

then I would like to delete let's say the first one and it should look like this:

tempArray:
[
  {id:"L-62961", description: "Book2"},
  {id:"L-70605", description: "Book3"}
]

How do I achieve this ?

UPDATE better visual: (I'm using tempLibrosData to play with another variable and not the main after it works with tempLibrosData then I'll use the main variable)

This is what I have:

let librosData = data[0].data
let tempLibrosData = librosData;

The Delete function

onClick={() => {
              const selectedIDs = new Set(selectionModel);
              librosData.filter((x) =>
              selectedIDs.has(x.id)).map( x => {
                console.log(x.id) //This prints the ID (in this case  L-2627)
                
                const res = tempLibrosData.filter(e => e.id != x.id)
                console.log(tempLibrosData) // This should print the final result and is printing so far all of them
              })
            }}

CodePudding user response:

You can use Array.filter:

const idToRemove = "L-2627"

tempArray = [
  {id:"L-2627", description: "Book1"},
  {id:"L-62961", description: "Book2"},
  {id:"L-70605", description: "Book3"}
]

const res = tempArray.filter(e => e.id != idToRemove)
console.log(res)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use MobX, and create and decorate a view model and the view (use mobx-react for that).

Then it's trivial.

  • Related