Remap a JavaScript Object

in code


Eh, gods, this one bothered me a fair bit. At work our API returns some data that I’ve found I have to remap. As it happens with any organically-grown system, there are a number of small inconsistencies between different objects with similar attributes. For example:

interface Foo {
  ices: {
    type: 'vanilla';
  }
}

interface Bar {
   icecream: 'vanilla';
}

interface Fizz {
   confectionaries: {
    ice_cream: 'vanilla';
  }
}

I want to map all of these consistently so I could call (say) foo.ices.type. For this I found schm’s translate method through a founder’s blog post. Using Lodash’s _.set to go with _.get, I can set arbitrary paths as well as being able to read from them:

import { get, isObject, set } from 'lodash';

function translate(source: object, map?: object): object {
  if (isObject(map)) {
    return Object.keys(map).reduce(
      (acc, key) => set(acc, key, get(source, map[key])),
      source
    );
  } else {
    return source;
  }
}

Example:

const map = {
  'ices.type' = 'confectionaries.ice_cream',
  'ices.taste' = 'appraisal.deliciousness'
};

My next step will be to create a higher-order function that takes the map and translates the passed object.



Coffee is Good

in code


Your email address will not be published. Required fields are marked *