I'm coding an app where the same data structure is saved a whole lot of times. Shortened example:
user-xyz: {
displayName: 'Bla',
email: '[email protected]',
preferences: {
education: 'high'
}
}
To save bandwidth and database storage, I wanted to 'minify' my database keys to:
user-xzy: {
dN: 'Bla',
e: '[email protected]'
p: {
e: 'high'
}
}
Now I have the problem that objects are coming from the database in a minified way, and I have to reassign the correct 'full' keys, so I can work with the object normally in my app. I don't want to work with the minified version, because it'd make it a lot harder for new coders to come in.
What is a good way to 'translate' the object when I have two e's (for example) as a minified key? I'd need to somehow include the object structure into my logic to select the appropriate full key.
EDIT: Redu's answer solved this problem. Now I realized, that I sometimes had objects with less keys, because the database wouldn't save 'null' values. Redu's answer wouldn't work anymore because it makes use of the index. However, I was able to modify his solution so it still works when keys are missing:
// mapping object
var userXYZ = {
displayName: 'dN',
email: 'e',
preferences: 'p',
p: {
education: 'e'
}
};
var userXYZMin = {
dN: 'myName',
// e: '[email protected]', -> missing key
p: {
e: 'elementary'
}
};
var restoreKeys = function (original, minified) {
return Object.keys(original)
.reduce(function (o, k) {
if (typeof original[k] !== "object")
o[k] = (typeof minified[original[k]] !== "object"
? minified[original[k]] || ""
: restoreKeys(original[original[k]], minified[original[k]]) || {});
return o;
}, {});
};
That just for future search requests :)
Provided that you don't have a duplicate keys at same levels then you may do as follows;
function restoreKeys(original,minified){
var oksm = Object.keys(minified);
return Object.keys(original)
.reduce((o,k,i) => typeof original[k] !== "object" ? (o[k] = minified[oksm[i]],o)
: (o[k] = restoreKeys(original[k],minified[oksm[i]]),o),{});
}
var userXYZ = {
displayName: 'Bla',
email: '[email protected]',
preferences: {
education: 'high'
}
},
userXYZMin = {
dN: 'myName',
e: '[email protected]',
p: {
e: 'elementary'
}
},
restored = restoreKeys(userXYZ,userXYZMin);
console.log(restored);
The following is the ES5 compatible version
function restoreKeys(original,minified){
var oksm = Object.keys(minified);
return Object.keys(original)
.reduce(function(o,k,i){
var oksm = Object.keys(minified);
o[k] = typeof original[k] !== "object" ? minified[oksm[i]]
: restoreKeys(original[k],minified[oksm[i]]);
return o;
}, {});
}
var userXYZ = {
displayName: 'Bla',
email: '[email protected]',
preferences: {
education: 'high'
}
},
userXYZMin = {
dN: 'myName',
e: '[email protected]',
p: {
e: 'elementary'
}
},
restored = restoreKeys(userXYZ,userXYZMin);
console.log(restored);