Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new Key/Value into Object in React Native

I'm working on a React Native project. Right now, I'm adding new key/value inside an object.

It's working but I would like to know if there is a better way to do it or if you have any advice.

I'm still new to ReactJS/React Native and not 100% skills on Javascript. So here's my code :

My object

state = {
    result : {
        "q1":1
    }
}

My function to add key/value and modify the state of result :

_getValue = (id, value) => {

    var newObj = this.state.result;
        newObj[id] = parseInt(value);

    this.setState({
        result: newObj
    }, () => {
        console.log(this.state.result)
    })
}

Thank you !

like image 573
Clément CREUSAT Avatar asked Sep 27 '18 13:09

Clément CREUSAT


People also ask

How do I add a key value to an array of objects?

To add a key/value pair to all objects in an array:Use the Array. map() method to iterate over the array. On each iteration, use the spread syntax to add the key/value pair to the current object. The key/value pair will get added to all objects in the new array.

Can a key be an object React?

Objects cannot be used as keys. React js requires a key to be a string or a number and should be unique.

How add key value pair in array React?

You create your object (including its id property) and then you add it to the result array. You add the id property to the last object in your result array (since you talk about "newly created data" I am assuming it is always the last item).


1 Answers

this should work fine.

this.setState({
  result: {
     ...this.state.result,
     [id]: value
  }
});

it uses modern/new features such as object spread (...this.state.result) and dynamic object properties ([id]: value)

like image 58
Dimitar Christoff Avatar answered Sep 21 '22 18:09

Dimitar Christoff