I have json object which i need to set/override some properties.
This part is done (i too the solution from this answer)
My problem now is handle the case the path to change is not given (or empty.)In this case it shoudl just return an empty Obj which i could then handle and return an error message.
var obj = { "users": {
"profile": {
"name": "markus",
"age": 28
}
}
}
var changes = [
{
path: ['users', 'profile', 'name'],
changes: "Nino"
},
{
path: [],
changes: "fail"
}
];
// Func to set new values
function set(jsonObj, path, value, updatedJson) {
if(path.length === 0 || value.length === 0) {
updatedJson = {};
return updatedJson;
}
if(path.length === 1){
updatedJson[path] = value;
} else {
for(var i = 0; i < path.length-1; i++) {
var elem = path[i];
if( !updatedJson[elem] ) {
updatedJson[elem] = {}
}
updatedJson = updatedJson[elem];
}
updatedJson[path[path.length-1]] = value;
}
return updatedJson;
}
var updatedJson = Object.assign(obj);
changes.forEach( function(changeObj){
var path = changeObj.path;
set(obj, path, changeObj.changes, updatedJson);
});
// handle empty object case
if(Object.keys(updatedJson).length === 0 && obj.constructor === Object){
callback({
success: false,
message: 'File not updated. One or more property are incorrect.'
})
} else {
callback({
success: updatedJson,
message: 'File was succefully updated'
})
}
Changes[0]
pass and set new value to the obj.
Changes[1]
should instead set updatedJson
to empty one, which it does but when i check if Object is empty, updatedJson
is full again.
Can someone explain me why is this happening?
And how can i handle error like empty path to object's value?