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.currentObjectis a property, and is not the variable with the same name.thisis not appropriate here. Just assign tocurrentObject.The variable
part2gets a value, but it is not used. So this doesn’t accomplish anything.The final assignment
currentObject = valuewill not affect themodelobject, only that local variable. So also this statement has no lasting effect.The
forloop iterates one time too many. You’d need to stop one step earlier so you can still assign thevalueto 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