Mikias Gebre
Mikias Gebre

Reputation: 1

How to filter array from a stacked array in react

I want to filter only the fields element to delete it. I already manage to delete the all of the data but I want the option to delete also only one value of the fields. I manage to filter the data by this piece of code

this.setState(
  state => ({
    data: state.data.filter((row, j) => j !== i),
  })
);

But I only want to delete one item from data.fields. I already tried to use this

this.setState(state => ({
  data: state.data.filter((row, j) => row.fields[x].bitname !== k),
}));

But I've not had luck yet.

Here is the data structure:

data: [
  {
    registerName: "MANID",
    address: 0,
    mode: "R",
    size: 8,
    por: 0,
    doc: "document level",
    fields: [
      { bitname: 'INT', bitmask: '16', bitvalue: '*', maskname: '*', doc: 'doc level' },
      { bitname: 'IDLE_MODE', bitmask: '0', bitvalue: '*', maskname: '*', doc: 'doc level' },
    ]
  }
]

Upvotes: 0

Views: 43

Answers (2)

EvanMorrison
EvanMorrison

Reputation: 1217

You should avoid deleting the field from the existing object because that mutates state directly. Try something like this.

this.setState(
      state => (
        {
          data: state.data.map((row, j) => {
              if (j === i) {
                return {
                  ...row,
                  fields: row.fields.filter(field => field.bitname !== k)
                }                
              }
              return row;
            }),
        })); 

Upvotes: 1

Vincent
Vincent

Reputation: 4753

If your object is row.fields[x] and you want to delete the bitname property from that object, the correct way to do it is:

delete row.fields[x].bitname

Here is an example snippet to delete a property from an object:

const field = {
  name:'Sean',
  age:25,
  bitname:'some value'
}

delete field.bitname

console.log(field)

Upvotes: 0

Related Questions