Search code examples
javascriptperformancejavascript-objects

What is the fastest way to sort/filter an object into multiple objects?


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"}
  • Each property is composed of the class name + '__' + property name.
  • The values are always strings.
  • inputData will never have more than a hundred properties

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.


Solution

  • 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.