Skip to content

Instantly share code, notes, and snippets.

@khoand0000
Last active January 1, 2016 05:31
Show Gist options
  • Save khoand0000/2e306d6199cf653f0509 to your computer and use it in GitHub Desktop.
Save khoand0000/2e306d6199cf653f0509 to your computer and use it in GitHub Desktop.
tap vs. mapObject
_.mixin({
mapObjectWithKeys: mapObjectWithKeys
});
/////////////////////
/**
* is similar to `.mapObject` but just apply `iteratee` for properties have key in `keys`
* Eg:
* var obj = {'x':'a', 'y':'5', 'z':'6'};
* _.mapObjectWithKeys(obj, parseInt, 'y', 'z') // {'x':'a', 'y':5, 'z':6}
* // _.mapObjectWithKeys(obj, parseInt, ['y', 'z']) // {'x':'a', 'y':5, 'z':6}
* @param {Object} obj
* @param iteratee
* @returns {Object}
*/

I have a object

var obj = {
  x: 'abc',
  y: '6',
  z: '8'
};

I want to convert y and z to int type. There are 2 ways:

  • Using .mapObject, I choose the way because when I want more keys, just change keys variable, no more lines
var keys = ['y', 'z'];
_.mapObject(obj, function(value, key) {
  return _.contains(keys, key) ? parseInt(value) : value;
});
  • Using .tap, just reference, If I want more keys, more lines, more code
_.tap(obj, function(obj){
  obj.y = parseInt(obj.y);
  obj.z = parseInt(obj.z);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment