@storm-stack/utilities
Version:
This package includes various base utility class and various functions to assist in the development process.
20 lines (19 loc) • 629 B
JavaScript
import { isObjectIndex, isString } from "@storm-stack/types";
import { toPath } from "./to-path.mjs";
export function setField(object, path, value) {
const resolvedPath = Array.isArray(path) ? path : isString(path) ? toPath(path) : [path];
let current = object;
for (let i = 0; i < resolvedPath.length - 1; i++) {
const key = resolvedPath[i];
const nextKey = resolvedPath[i + 1];
if (current[key] === null) {
current[key] = isObjectIndex(nextKey) ? [] : {};
}
current = current[key];
}
const lastKey = resolvedPath.at(-1);
if (lastKey) {
current[lastKey] = value;
}
return object;
}