Answer the question
In order to leave comments, you need to log in
How to dynamically create an object?
Good afternoon! Such a situation: there is such an interface:
interface IParams {
value?: number;
current?: number;
}
interface IObj {
params?: IParams;
age?: number;
animal?: string;
}
{
params: {
value: 5
}
}
const paths = {
value: ['params','numberic', 'value'],
current: ['params', 'current'],
age: null,
animal: null
}
const keysArray = Object.keys(paths);
const obj: IObj = {}
const toEnter = { value: 5}
const tail = ([, ...t]: string[]) => t;
const head = ([h]: string[]) => h;
const make = (path: string[], value: any, intermediat: object) => {
if (path.length === 1) {
return intermediat[path[0]] = value
} else {
obj[head(path)] = {}
make(tail(path), value, obj[head(path)]);
}
}
for (const keyToInput in toEnter) {
if (keysArray.indexOf(keyToInput) > -1) {
if (paths[keyToInput] !== null) {
make(paths[keyToInput], toEnter[keyToInput], {});
} else {
obj[keyToInput] = toEnter[keyToInput]
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question