实施Lodash反转

我正在解决一个挑战,要求我自己实现.invert()方法。以下是我的解决方案,但预期结果与返回的实际结果不匹配。请参阅下面的第二块。

实现.invert()方法:

const _ = {invert (object){
let newObject = {};
for (let key in object){
const originalValue = object[key]
newObject = {originalValue: key}
}
return newObject;
}};

经过以下代码测试:

var obj1 = { 'a': '1', 'c': '1', 'b': '2' };
console.log(_.invert(obj1));

我希望看到以下返回:

{ '1': 'c', '2': 'b' }

实际返回值如下:

{ originalValue : 'c'}

我做错了什么,但不知道该怎么办...有人可以帮忙吗?

评论
  • _堅=強
    _堅=強 回复

    Solve this using reduce.

    var obj = { 'a': '1', 'c': '1', 'b': '2' };
    const res = Object.entries(obj).reduce((a, [k, v]) => ({...a, [v]: k}), {});
    
    console.log(res);
  • sunde
    sunde 回复

    Convert to an array of pairs of [key, value] using Object.entries(), then map and and flip the pairs to [value, key]. Convert back to an object using Object.fromEntries():

    const obj = { 'a': '1', 'c': '1', 'b': '2' };
    
    const result = Object.fromEntries(
      Object.entries(obj)
        .map(([k, v]) => [v, k])
    )
    
    console.log(result);
  • id_aut
    id_aut 回复

    instead of assigning a new value for newObject'every loop, try just adding a new key to the current object:

    const _ = {
      invert (object) {
        let newObject = {};
    
        for (let key in object){
          const originalValue = object[key];
          newObject[originalValue] = key;
        }
    
        return newObject;
      }
    };