Advertisement
Guest User

Untitled

a guest
Feb 6th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. function mapObj(obj, cb) {
  2. var mappedObject = null;
  3. var mappedArray = Object.keys(obj).map(function(e, i, a) {
  4. var mapped = cb(e, obj[e], i);
  5. if (mappedObject !== false && Array.isArray(mapped) && mapped.length === 2) {
  6. if (!mappedObject) {
  7. mappedObject = { };
  8. }
  9. mappedObject[mapped[0]] = mapped[1];
  10. // always do the work of normal array mapping, I guess
  11. } else { // any instance of non object-map response aborts assembly of mappedObject
  12. if (mappedObject) { // not false and not null, therefore is object
  13. // here is where we might implement going back to re-assemble·
  14. // mappedObject into mappedArray but we're actually always·
  15. // building mappedArray so for now we must do exactly nothing
  16. }
  17. mappedObject = false;
  18. }
  19. return mapped;
  20. });
  21. return mappedObject || mappedArray;
  22. }
  23.  
  24. // a scary thing, albeit with effort expended to make it "safe" with
  25. // a overwrite-check.
  26. if (!Object.prototype.map) {
  27. Object.defineProperty(Object.prototype, 'map', {
  28. value: function(cb) {
  29. return mapObj(this, cb);
  30. },
  31. writable: true,
  32. configurable: true,
  33. enumerable: false
  34. });
  35. }
  36.  
  37.  
  38. var test = function () {
  39. somevar = {method:'value', blargle: 325234, 34234: 222};
  40. console.log(JSON.stringify(somevar.map(function(k,v){ return {key: k, val: v} })));
  41. console.log(JSON.stringify(somevar.map(function(k,v){ return ['map'+k, v+'map'] })));
  42.  
  43. // You shall expect:
  44. // [{"key":"34234","val":222},{"key":"method","val":"value"},{"key":"blargle","val":325234}]
  45. // {"map34234":"222map","mapmethod":"valuemap","mapblargle":"325234map"}
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement