Code:
module.exports.set = function (data, key, value) {
if (key.includes(".")) {
let elements = key.split(".");
let element = elements.pop();
let obj = elements.reduce((object, keyy) => {
if (typeof object[keyy] == "undefined") object[keyy] = {};
return object[keyy];
}, data);
obj[element] = value;
return data;
} else {
data[key] = value;
return data;
}
}
I'm going to explain the problem to you with examples.
var obj = {};
set(obj, "hello.world", "test")
console.log(obj)
The console log:
{
"hello": {
"world": "test"
}
}
But if I write this code:
var obj = {
"hello": {
"world": "test"
}
};
set(obj, "hello.world.again", "hello again")
console.log(obj)
There is no change in the object. The console log will be this:
var obj = {
"hello": {
"world": "test"
}
};
I wanna the result like this:
{
"hello": {
"world": {
"again": "test"
}
}
}
In lodash module, I can do the I told things. But in my code I can't do that. Please help me, how can I do this?