Skip to content
Advertisement

javascript typescript create a object

i have a property like this “data.property” = “16165456”.. i try to create a object like this

data {
   property : "16"
}

i use split and and loop but not work

    this.returnKey(model, this.to['pro1'], this.model[this.to['pro2']])
returnKey(model: any, name: string, value: string) {

        let nameParts = name.split("."),
            currentObject = model;
        for (let i in nameParts) {
            let part = nameParts[i]
            currentObject[part] = currentObject[part]

            this.currentObject = currentObject[part];
        }

        let part2 = nameParts[1];
        currentObject = value;
    }

Advertisement

Answer

A few issues:

  • currentObject[part] = currentObject[part] is a statement that accomplishes nothing. You’d want to indicate what to assign when that property does not yet exist, so do:

    currentObject[part] = currentObject[part] ?? {};
    
  • this.currentObject is a property, and is not the variable with the same name. this is not appropriate here. Just assign to currentObject.

  • The variable part2 gets a value, but it is not used. So this doesn’t accomplish anything.

  • The final assignment currentObject = value will not affect the model object, only that local variable. So also this statement has no lasting effect.

  • The for loop iterates one time too many. You’d need to stop one step earlier so you can still assign the value to the property of the parent object that needs to get it.

Here is a correction to all those issues:

function returnKey(model, name, value) {
    let nameParts = name.split("."),
        key = nameParts.pop(), // extract the last property
        currentObject = model;
    for (let i in nameParts) { // Now we will iterate one time less
        let part = nameParts[i];
        // Initialise the property with `{}` when it is new:
        currentObject[part] = currentObject[part] ?? {};
        currentObject = currentObject[part];
    }
    // Assign to the deepest key, so the model will get it:
    currentObject[key] = value;
}

// Demo:
let name = "data.numeroApplication";
let value = "16165456";
let model = {};
returnKey(model, name, value);
console.log(model); // Model has mutated
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement