3

I have a dictionary named CarValues in my code which contains following data: CarValues is a dictionary initialized in the state.

dictionary: CarValues

key ==> string

Value ==> Array

key => Honda, Value => white, yellow, red, orange
key => Toyota, Value => white, yellow, green, black
Key => Volkswagen Value => 123, 456, 343

I would like to delete Honda and its value completely from CarValues. Though, I see few similar questions, I couldn't find the best solution for this question.

How can I remove an attribute from a Reactjs component's state object

Vicky
  • 624
  • 2
  • 12
  • 35
  • As for deleting an object (dictionary) attribute, you can use `delete obj[attr]`. If your question is about changing a React component state, then you should add your state structure and explain more what the problem is. – kaveh Mar 05 '18 at 05:00

7 Answers7

6

This should solve your issue

yourMethod(key) {
  const copyCarValues= {...this.state.CarValues}
   delete copyCarValues[key]
  this.setState({
     CarValues: copyCarValues,
  })
}
simbathesailor
  • 3,681
  • 2
  • 19
  • 30
  • shouldn't it be `delete copyCarValues[key]`instead of `delete CarValues[key]`? – izengod Mar 05 '18 at 05:31
  • I have one question: Wouldn't delete this.state.CarValues[this.state.key] solve it directly. Why do we have to create a copy and delete the item and then update the state. Sorry I am new to the front end and UI stuff. Pardon my question if it is lame. – Vicky Mar 05 '18 at 05:41
  • Reacts state is meant to be immutable meaning you never change the state, you replace the entire state if you want to make a change. @Vicky – Francis Malloch Mar 05 '18 at 06:03
1

I believe in order to truly do this without mutating the state, you will need to re-create the entire state like so.

class Test extends React.Component {
  state = {
    thingToDelete: {},
    otherStuff: {}
  };

  deleteThingToDelete = () => {
    const {thingToDelete, ...state} = this.state;
    this.setState(state);
  }
}

Using the spread operator, we achieve a shallow clone, so be wary about that. The other option is to use Object.assign but that will also only offer a shallow clone but you will achieve much better browser support.

Francis Malloch
  • 1,074
  • 9
  • 20
1

Probably arriving here a bit late, but here is a way of doing this with hooks and without actually mutating the previous state.

const sampleItems = {
  'key1': { id: 1, name: 'test'},
  'key2': { id: 2, name: 'test2'},
}

const Test = props => {
  const [items, setItems] = useState(sampleItems);

  deleteItemFromStateObject = itemKey => {
    setItems(({[itemKey]: toDelete, ...rest}) => rest);
  }
}
0

The easiest way to do this would be:

const carValues = Object.assign({}, this.state.carValues)
delete carValues[key]
this.setState({ carValues })
Tyler
  • 567
  • 5
  • 5
0

You can use Underscore.js or Lodash http://underscorejs.org/#omit

_.omit(copyCarValues, 'Honda'); 
David
  • 15,894
  • 22
  • 55
  • 66
0

First Initialise Array Globally

var dict = []

Add Object into Dictionary

dict.push(
     { key: "One",value: false},
     { key: "Two",value: false},
     { key: "Three",value: false});

Output : 
   [0: {key: "One", value: false},
    1: {key: "Two", value: false},
    2: {key: "Three", value: false}]

Update Object from Dictionary

Object.keys(dict).map((index) => {        
  if (index == 1){
    dict[index].value = true
  }
});

Output : 
   [0: {key: "One", value: false},
    1: {key: "Two", value: true},
    2: {key: "Three", value: false}]

Delete Object from Dictionary

Object.keys(dict).map((index) => {              
      if (index == 2){
        dict.splice(index)
      }
    });

Output : 
    [0: {key: "One", value: false},
     1: {key: "Two", value: true}]
Pratik Panchal
  • 339
  • 5
  • 13
0

Here is another simple enough solution to achieve this.

const myCarsValueInState = this.state.myCarsValueInState;
    Object.keys(myCarsValueInState).map((index) => {
      myCarsValueInState[index] = undefined; // you can update on any condition if you like, this line will update all dictionary object values. 
      return myCarsValueInState;
    });

Simple enough.

A.J.
  • 8,557
  • 11
  • 61
  • 89