score:4
Accepted answer
one way to achieve this would be to acquire the nested object that is the parent of the field that your path is targeting via array#reduce
:
const nestedobject = path
.slice(0, -1)
.reduce((object, part) => (object === undefined ? undefined : object[part]), { ...state })
and then update the last key/value of nestedobject
by via the last key of your path:
/* get last part of path, and update nestedobject's value for this key, to 2 */
const [pathtail] = path.slice(-1);
nestedobject[pathtail] = 2;
the following snippet shows these two ideas together:
/* path of nested field to update, in array notation */
const path = ['mango', 'banana', 'a'];
/* components state */
const state = {
apple: {
a: 1,
b: 2,
},
mango: {
banana: {
a: 1,
b: 2,
}
}
};
const stateclone = { ...state };
/* aquire the parent object (ie banana) of the target field (ie a) */
const nestedobject = path
.slice(0, -1)
.reduce((object, part) => (object === undefined ? undefined : object[part]), stateclone)
if (nestedobject !== undefined) {
/* obtain last key in path */
const [pathtail] = path.slice(-1);
/* update value of last key on target object to new value */
nestedobject[pathtail] = 2;
}
/* display updated state */
console.log('updated state:', stateclone)
/* call this.setstate: */
// this.setstate(stateclone);
update
here is some extra detail outlining how the reduce()
part of the answer works:
path
/* slice obtains ['mango', 'banana'], seeing -1 clips last item */
.slice(0, -1)
/* reduce iterates through each part of array ['mango', 'banana']
where at each iteration we fetch the corresponding nested object
of the { ...state } object that's passed in */
.reduce((object, part) => {
/* at iteration 1:
object has two keys, 'apple' and 'mango'
part is 'mango'
object is defined, so return object['mango'] for first iteration
at iteration 2:
object passed from last iteration has one key, 'banana'
part is 'banana'
object is defined, so return object['banana'] for second iteration
reduce complete:
we return object['banana'], which is the same as state['mango']['banana']
*/
if(object === undefined) { return undefined; }
return object[part]
}, stateclone)
score:0
having:
const [formstate, setformstate] = usestate(
{
id:1,
name:'name',
innerobjectname: {
propa: 'something',
propb: 'another thing',
}
});
maybe you're looking for something like this:
const handlecomplexinputchange = (evt, object) => {
setformstate({
...formstate,
[object] : {
...formstate[object],
[evt.target.name]: evt.target.value,
}
})
}
and from your component you should call it like this:
onchange={(e) => {
handlecomplexinputchange(e, "innerobjectname");
}}
Source: stackoverflow.com
Related Query
- ReactJS: How to access and update nested state object with dynamic key?
- React hooks: How do I update state on a nested object with useState()?
- ReactJS setState with multidimensional object and dynamic key
- How to change the value with all specific key in the nested state in ReactJS
- How to update state of nested object by id with input select method?
- In Reactjs how do I update the correct value in the parent state with a callback that's been passed to a nested child component?
- How to access Nested Object with Map in ReactJS
- Reactjs - How to access nested keys in a json with dynamic values
- How to set an an object with a dynamic key as React state in Typescript
- ReactJS - how do I update nested and "normal" state properties?
- Applying State to Nested Object in React. How do I call API and display with Use Effect
- How can I add new a new object with key and values pairs to the existing state in class based component?
- How to update certain key values in an object nested in the redux state
- How to access JSON object key and value in ReactJS
- Deleting property from state object with key interpolation and destructuring
- How to properly update state with Firebase and useEffect()?
- How to test redux state update with react testing library and jest
- How can i get array of object from this data for state and count in reactjs
- Calling setState with nested object does not update state correctly
- Redux - Find object in state array by its key and update its another key
- React js useState hook. How to update state of a json object with an a array in it when a checkbox is clicked
- How to update the state of nested json object in react using hooks
- ReactJS iterate through state array with dynamic key with its data
- How to run React useEffect only once and property update state with setState
- How to assign a value to state and use setState in ReactJs with Typescript
- update nested state object with array inside
- Initialize state with dynamic key based on props in reactJS
- How to update array within state object with react/redux
- How can I format an excel file with empty rows to have nested arrays and match a JSON object that I need to render?
- Update specific state with given key and value?
More Query from same tag
- Reactjs: How to pass user input from different files?
- React component displaying different props than given
- How to get parent props/state from grandchild in reactjs
- Reactjs map function mapping more elements than the ones present in array
- React hide header component for some routes
- How to detect if a user is using a tv app?
- React Text Annotation
- React filtering array of object by input text and category selection by button click
- render simple HTML with react.cloneElement
- Konva Line Not Appearing
- How can I use medium widget in a React website
- Cant seem to parse json data in React, unsure of any conceptual errors i might
- Fire function from one react component in another
- Make Card (or Paper) NOT take up full width Material UI
- Hot to show IconButton inside MenuItem but not if it selected
- How to Integrate Google Calendar API with React JS?
- React UseEffect - How to empty an array when i select an Item from dropown
- react-router children not propagating
- How can I prevent to add data if the object property value is different using react js
- React-Router redirect after auth I'm getting infinite loop of renders
- How to avoid overrated item after set state?
- How can i get specific user data from firestore in React?
- How to push an object inside nested array using React and TypeScript?
- Why am I making an invalid hook call?
- React hooks: Issue with React.memo and useState
- How to close modal in react hooks?
- How to avoid letting an async thunk that is no longer useful (the app is not expecting it anymore) from being able to update the state?
- Change values of an object
- Redux- Form: Unable to Dispatch Action on Submit
- Show/Hide Input field on checkbox onchange