Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function mapObj(obj, cb) {
- var mappedObject = null;
- var mappedArray = Object.keys(obj).map(function(e, i, a) {
- var mapped = cb(e, obj[e], i);
- if (mappedObject !== false && Array.isArray(mapped) && mapped.length === 2) {
- if (!mappedObject) {
- mappedObject = { };
- }
- mappedObject[mapped[0]] = mapped[1];
- // always do the work of normal array mapping, I guess
- } else { // any instance of non object-map response aborts assembly of mappedObject
- if (mappedObject) { // not false and not null, therefore is object
- // here is where we might implement going back to re-assemble·
- // mappedObject into mappedArray but we're actually always·
- // building mappedArray so for now we must do exactly nothing
- }
- mappedObject = false;
- }
- return mapped;
- });
- return mappedObject || mappedArray;
- }
- // a scary thing, albeit with effort expended to make it "safe" with
- // a overwrite-check.
- if (!Object.prototype.map) {
- Object.defineProperty(Object.prototype, 'map', {
- value: function(cb) {
- return mapObj(this, cb);
- },
- writable: true,
- configurable: true,
- enumerable: false
- });
- }
- var test = function () {
- somevar = {method:'value', blargle: 325234, 34234: 222};
- console.log(JSON.stringify(somevar.map(function(k,v){ return {key: k, val: v} })));
- console.log(JSON.stringify(somevar.map(function(k,v){ return ['map'+k, v+'map'] })));
- // You shall expect:
- // [{"key":"34234","val":222},{"key":"method","val":"value"},{"key":"blargle","val":325234}]
- // {"map34234":"222map","mapmethod":"valuemap","mapblargle":"325234map"}
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement