S
S
Slav4ka2020-04-15 09:49:21
JavaScript
Slav4ka, 2020-04-15 09:49:21

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;
}

You need to write a function that creates an object only with the key that came. That is, if the key value came, then the object should look like this:
{ 
    params: { 
        value: 5
    }
}

I tried this implementation, but if the nesting is more than 2, it does not work.

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 question

Ask a Question

731 491 924 answers to any question