You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
export function set(object, path, value) { // object is observable, path is "users[1].name", value is "shivamm"
let index = -1; // Index to iterate through the path keys
const tempPath = isKey(path) ? [path] : stringToPath(path); // Convert path to array of keys
const length = tempPath.length; // Length of the path
const lastIndex = length - 1; // Last index of the path
while (++index < length) {
const key = tempPath[index]; // Current key in the path
let newValue = value; // Value to be set at the end of the path
// If not the last index, determine what type of structure is needed
if (index !== lastIndex) {
const objValue = object[key];
newValue = isObject(objValue) || Array.isArray(objValue) // If it's an object or array, keep it
? objValue
: !isNaN(+tempPath[index + 1]) // If the next key is numeric, create an array
? []
: {}; // Otherwise, create an object
}
object[key] = newValue; // Set the key's value
object = object[key]; // Move to the next level in the object
}
}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Beta Was this translation helpful? Give feedback.
All reactions