Reputation: 341
I have an object that looks like this that I want to split out and put each property into its relevant class:
inputData = {contact__name:"john",othercontact__name:"sue",othercontact2__name:"joe",company__id:"123"}
Currently I do something like this, but I feel like this may not be the best or fastest way of going about it.
const contact = new Contact(), othercontact = new Contact(), company = new Company(), custom = new Custom();
const sortInputIntoObjects = (_inputData) => {
let subkey = [];
const tempObj = {};
for (key in _inputData) {
subkey = key.split('__');
switch (subkey[0]) {
case 'contact': {
contact[subkey[1]] = _inputData[key];
break;
}
case 'othercontact': {
othercontact[subkey[1]] = _inputData[key];
break;
}
case 'company': {
company[subkey[1]] = _inputData[key];
break;
}
default: {
custom[subkey[1]] = _inputData[key];
}
}
}
};
After the sorting, each object gets sent to its relative API.
Is there a better way of doing this? Perhaps a map/reduce/filter or is this best as is?
NOTE: this is for Zapier code and can only be ES8 on V8 and cannot use external libraries.
Upvotes: 0
Views: 58
Reputation: 665122
No point in pre-initialising subkey
and tempObj
, and the switch
/case
can be simplified using a lookup object (or Map
):
function sortInputIntoObjects(inputData) {
const contact = new Contact(),
othercontact = new Contact(),
company = new Company(),
custom = new Custom();
const objects = {contact, othercontact, company};
for (const key in inputData) {
const subkey = key.split('__');
const object = objects[subkey[0]] ?? custom;
object[subkey[1]] = _inputData[key];
}
}
This may or may not be faster, but it's certainly simpler.
Upvotes: 1