Skip to content

Instantly share code, notes, and snippets.

@carloscarucce
Created November 21, 2025 12:48
Show Gist options
  • Select an option

  • Save carloscarucce/0b4a86a79d753b292ee1c56bfddeaa19 to your computer and use it in GitHub Desktop.

Select an option

Save carloscarucce/0b4a86a79d753b292ee1c56bfddeaa19 to your computer and use it in GitHub Desktop.
Dynamic object state control for React Components
export default const MyComponent => () => {
const [formData, setFormData] = useState({});
const removeFormData = (path) => {
setFormData(prev => {
const newData = structuredClone(prev);
const keys = path.split(".");
let obj = newData;
keys.forEach((key, idx) => {
const isLast = idx === keys.length - 1;
// Convert numeric keys to actual numbers
const numericKey = !isNaN(Number(key)) ? Number(key) : key;
if (isLast) {
// If final key is an array index → remove from array
if (Array.isArray(obj) && typeof numericKey === "number") {
obj.splice(numericKey, 1);
}
// Otherwise delete object property
else {
delete obj[numericKey];
}
} else {
obj = obj[numericKey];
if (obj == null) return newData; // path doesn't exist → nothing to remove
}
});
return newData;
});
};
const handleInputChange = (path, value) => {
setFormData(prev => {
const newData = structuredClone(prev); // or deep clone however you prefer
const keys = path.split(".");
let obj = newData;
keys.forEach((key, idx) => {
const isLast = idx === keys.length - 1;
const nextKey = keys[idx + 1];
const isNextIndex = !isLast && !isNaN(Number(nextKey));
// If key is array index
if (!isNaN(Number(key))) {
key = Number(key);
}
if (isLast) {
obj[key] = value;
} else {
if (obj[key] == null) {
// Create array or object depending on next segment
obj[key] = isNextIndex ? [] : {};
}
obj = obj[key];
}
});
return newData;
});
};
//Example
handleInputChange('test.0.name', 'name'); //set index/value
removeFormData('test.0.name'); // remove index
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment