In React's this.state I have a property called formErrors
containing the following dynamic array of objects.
[ {fieldName: 'title', valid: false}, {fieldName: 'description', valid: true}, {fieldName: 'cityId', valid: false}, {fieldName: 'hostDescription', valid: false}, ]
Let's say I would need to update state's object having the fieldName cityId
to the valid value of true
.
What's the easiest or most common way to solve this?
I'm OK to use any of the libraries immutability-helper, immutable-js etc or ES6. I've tried and googled this for over 4 hours, and still cannot wrap my head around it. Would be extremely grateful for some help.
To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is.
There is one way to make an immutable array in Java: final String[] IMMUTABLE = new String[0]; Arrays with 0 elements (obviously) cannot be mutated. This can actually come in handy if you are using the List.
Immutable environment updates are an alternative to rolling updates. Immutable environment updates ensure that configuration changes that require replacing instances are applied efficiently and safely. If an immutable environment update fails, the rollback process requires only terminating an Auto Scaling group.
You can use map
to iterate the data and check for the fieldName, if fieldName is cityId then you need to change the value and return a new object otherwise just return
the same object
.
Write it like this:
var data = [ {fieldName: 'title', valid: false}, {fieldName: 'description', valid: true}, {fieldName: 'cityId', valid: false}, {fieldName: 'hostDescription', valid: false}, ] var newData = data.map(el => { if(el.fieldName == 'cityId') return Object.assign({}, el, {valid:true}) return el }); this.setState({ data: newData });
The left is the code, and the right is the output
Here is the code below
const data = [ { fieldName: 'title', valid: false }, { fieldName: 'description', valid: true }, { fieldName: 'cityId', valid: false }, // old data { fieldName: 'hostDescription', valid: false }, ] const newData = data.map(obj => { if(obj.fieldName === 'cityId') // check if fieldName equals to cityId return { ...obj, valid: true, description: 'You can also add more values here' // Example of data extra fields } return obj }); const result = { data: newData }; console.log(result); this.setState({ data: newData });
Hope this helps, Happy Coding!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With