The Wayback Machine - https://web.archive.org/web/20210126045255/https://github.com/Advanced-Frontend/Daily-Interview-Question/issues/431
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 162 题:实现对象的 Map 函数类似 Array.prototype.map #431

Open
NieZhuZhu opened this issue Nov 1, 2020 · 10 comments
Open

第 162 题:实现对象的 Map 函数类似 Array.prototype.map #431

NieZhuZhu opened this issue Nov 1, 2020 · 10 comments

Comments

@NieZhuZhu
Copy link

@NieZhuZhu NieZhuZhu commented Nov 1, 2020

列如:

// 实现一个 map 函数
const targetData = {
  a: 2,
  b: 3,
  c: 4,
  d: 5
};
const objMap = (obj, fn) => {
  if (typeof fn !== "function") {
    throw new TypeError(`${fn} is not a function !`);
  }
  return JSON.parse(JSON.stringify(obj, fn));
};
objMap(targetData, (key, value) => {
  if (value % 2 === 0) {
    return value / 2;
  }
  return value;
});
// {a: 1, b: 3, c: 2, d: 5}

参考:

你不知道的 JSON.stringify() 的威力

@Mrcxt
Copy link

@Mrcxt Mrcxt commented Nov 3, 2020

列如:

// 实现一个 map 函数
const targetData = {
  a: 2,
  b: 3,
  c: 4,
  d: 5
};
const objMap = (obj, fn) => {
  if (typeof fn !== "function") {
    throw new TypeError(`${fn} is not a function !`);
  }
  return JSON.parse(JSON.stringify(obj, fn));
};
objMap(targetData, (key, value) => {
  if (value % 2 === 0) {
    return value / 2;
  }
  return value;
});
// {a: 1, b: 3, c: 2, d: 5}

参考:

你不知道的 JSON.stringify() 的威力

这个实现有问题,首先JSON.stringify(obj, fn)中第一次传入fn中的参数为 ""和对象本身,从第二次开始才会传入key和val,所以应该加上条件处理。

(() => {

    Object.prototype._map = function (fn, oThis = null) {
        if (typeof fn !== 'function') {
            throw new TypeError(`${fn} is not a function !`)
        }
        return JSON.parse(JSON.stringify(this, (key, val) => {
            if (key) {
                return fn.call(oThis, key, val, this)
            } else {
                return val
            }
        }))
    }
    // 用例
    let obj = {
        a: 2,
        b: 3,
        c: 4,
        d: 5
    };
    let _obj = obj._map((key, val, o) => {
        return ++val
    })
    console.log(_obj);
})();
@NieZhuZhu
Copy link
Author

@NieZhuZhu NieZhuZhu commented Nov 3, 2020

列如:

// 实现一个 map 函数
const targetData = {
  a: 2,
  b: 3,
  c: 4,
  d: 5
};
const objMap = (obj, fn) => {
  if (typeof fn !== "function") {
    throw new TypeError(`${fn} is not a function !`);
  }
  return JSON.parse(JSON.stringify(obj, fn));
};
objMap(targetData, (key, value) => {
  if (value % 2 === 0) {
    return value / 2;
  }
  return value;
});
// {a: 1, b: 3, c: 2, d: 5}

参考:
你不知道的 JSON.stringify () 的威力

这个实现有问题,首先 JSON.stringify (obj, fn) 中第一次传入 fn 中的参数为 "" 和对象本身,从第二次开始才会传入 key 和 val,所以应该加上条件处理。

(() => {

    Object.prototype._map = function (fn) {
        if (typeof fn !== 'function') {
            throw new TypeError(`${fn} is not a function !`)
        }
        return JSON.parse(JSON.stringify(this, (key, val) => {
            if (key) {
                return fn.call(this, key, val)
            } else {
                return val
            }
        }))
    }
    // 用例
    let obj = {
        a: 2,
        b: 3,
        c: 4,
        d: 5
    };
    let _obj = obj._map((key, val) => {
        return ++val
    })
    console.log(_obj);
})();

对的,虽然不会被 JSON.stringify 返回但是做个判断总是好的

@Cecilxx
Copy link

@Cecilxx Cecilxx commented Nov 9, 2020

Object.prototype.map= function(cb) {
    const obj = this
    const result = {}
    for(key in obj) {
        if (obj.hasOwnProperty(key)) {
            const item = cb(key, obj[key])
            result[key] = item
        }
    }
    return result
}
const test1 = {
  a: 2,
  b: 3,
  c: 4,
  d: 5
};
const r1 = test1.map(() => {
   if (value % 2 === 0) {
    return value / 2;
  }
  return value;
})
// r1 :  {a: 1, b: 3, c: 2, d: 5}

const test2 = {
 a: 2,
 b: 3,
 c: 4,
 d: 5
};
const r2 = test2.map((key, val) => {
  return ++val
})
// r2: {a: 3, b: 4, c: 5, d: 6}
@FatDoge
Copy link

@FatDoge FatDoge commented Nov 10, 2020

const targetData = {
  a: 2,
  b: 3,
  c: 4,
  d: 5
};

Object.prototype.map = function(fn) {
  const res = {}
  for(e in this) {
    if(this.hasOwnProperty(e)) {
      res[e] = fn(this[e])
    }
  }
  return res
}

const p = targetData.map(e => e + 1)
console.log(p)
@Iam-llq-0007-xq
Copy link

@Iam-llq-0007-xq Iam-llq-0007-xq commented Nov 10, 2020

Object.prototype.map = function(fn) {
  const deepclone = JSON.parse(JSON.stringify(this));
	return Object.keys(deepclone).reduce((result, key, index) => {
  	result[key] = fn(deepclone[key], key, index);
    return result;
  }, {})
}

const obj = {
	a: 1,
  b: 2,
  c: 3,
}
const newObj = obj.map((value, key, index) => ({ [key]: value + ',,,' }));
console.log(newObj);
@JianJroh
Copy link

@JianJroh JianJroh commented Nov 24, 2020

为什么怎么多人搞深克隆🙄

参考自JavaScript Array map() 定义与用法 https://www.runoob.com/jsref/jsref-map.html

Object.prototype.map = function (handleFn,thisValue) {
    const obj = this;
    let res = {};
    for (let prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            res[prop] = handleFn.call(thisValue,obj[prop], prop,obj);
        }
    }
    return res;
};
// 测试用例
var obj = {
    name: 'sunny',
    sex: 'man'
};
var res = obj.map(function(val, prop,obj){
    console.log(this);
    console.log(val, prop,obj);
    return prop + '--' + val;
}, {name: 'thisthis'});
console.log('res:',res);
@getOnce
Copy link

@getOnce getOnce commented Nov 24, 2020

Object.prototype.map = function(handleFn){
return Object.keys(this).reduce((newObj, key) => {
return newObj[key] = handleFn(this[key], key, this);
}, {})
}

@linrunzheng
Copy link

@linrunzheng linrunzheng commented Dec 4, 2020

function objMap(source, cb) {
  return Object.keys(source).reduce((pre, key) => {
    pre[key] = cb(key, source[key], source);
    return pre;
  }, {});
@ganp1020
Copy link

@ganp1020 ganp1020 commented Dec 13, 2020

Object.prototype.map = function (fn) {
    let result = {}
    for (const key in this) {
        if (this.hasOwnProperty(key)) {
            const element = this[key]
            result = fn.call(this, key, element)
        }
    }
    return result
}


let res = obj.map((key, val) => {
    return {
        key, val
    }
})
@zfowed
Copy link

@zfowed zfowed commented Jan 25, 2021

Object.prototype.map = function (iteratee) {
  const result = {}
  for (const key of Object.keys(source)) {
    result[key] = iteratee.call(this, source[key], key)
  }
  return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
10 participants