I am implementing a recursive encryption for Javascript objects but the solution I came up with is non-functional. This has caused some weird errors as it manipulates the object directly. Is there any way to make this functional (return a new encypted object)?
I am at a loss on how to make this stay recursive and at the same time return a new object (functional). Specifically this is encryptObject(dd)
class Security {
static encryptText = (text) => {
//function to encrypt text/strings
};
static encryptObject(dd) {
try {
for (let d in dd) {
if (!dd[d]) {
continue;
} else if (typeof dd[d] !== "object") {
dd[d] = this.encryptText(dd[d]);
} else {
this.encryptObject(dd[d]);
}
}
} catch (e) {
console.log(e.message `error encrypting`);
}
}
const data = {dog:"john", cat:"anders", weapons:{laser:"3",sword:"1"}}
Security.encrypt(data)
I would like to call the function like this instead
const data = {dog:"john", cat:"anders", weapons:{laser:"3",sword:"1"}}
const encryptedData = Security.encrypt(data)
CodePudding user response:
Just create and return a new object instead?
static encryptObject(objectToEncrypt) {
try {
const newObj = {};
for (const [key, value] of Object.entries(objectToEncrypt)) {
if (!value) {
newObj[key] = value;
} else if (typeof value !== "object") {
newObj[key] = this.encryptText(value);
} else {
newObj[key] = this.encryptObject(value);
}
}
return newObj;
} catch (e) {
console.log(e.message `error encrypting`);
}
}