使用javascript更高阶函数简化对象转换

时间:2018-05-18 00:25:57

标签: javascript undefined transformation higher-order-functions

目标:我正在努力降低对象转换的复杂性。我被告知要使用更高阶函数来降低复杂性。我主要看的是代码块以简化,但任何其他指针或帮助将不胜感激。

问题:即使使用更高阶函数,我也没有看到明确的简化方法。

注意:我不能保证拥有所有字段,所以我需要防止密钥未定义。这就是为什么我在做(模型)=>如果我确认密钥存在,则model.key只读取属性。

模型:

{ 
  "origName1": "val1",
  "origName2": "val2",
  "origName3": "val3",<-- this key value is not always present
  "origName4": "val4"  
}

我的转型对象:

let transFormObj = {};
transFormObj.origName1= {'newKey': 'newName1', 'value': (model) => model.origName1};
transFormObj.origName2= {'newKey': 'newName2', 'value': (model) => model.origName2};
transFormObj.origName3= {'newKey': 'newName3', 'value': (model) => model.origName3};
transFormObj.origName4= {'newKey': {parentKey: 'newObj', childKey: 'newName4'}, 'value': (model) => model.origName4};

我关注的for block:

 let returnObj = {}
        for(let key in model) {
            if(key in transFormObj) {
                // is nested object?
                if(typeof(transFormObj[key].newKey) === 'object') {
                    // if parent key doesn't exist create else keep it the same
                    returnObj[transFormObj[key].newKey.parentKey] = returnObj[transFormObj[key].newKey.parentKey] || {};
                    returnObj[transFormObj[key].newKey.parentKey][transFormObj[key].newKey.childKey] = transFormObj[key].value(model);
                } else {
                returnObj[transFormObj[key].newKey] = transFormObj[key].value(model);}
            }
        }

预期输出对象:

{ 
      "newName1": "val1",
      "newName2": "val2",
      "newName3": "val3",
      "newObj": {"newName4" :"val4"}  
    }

1 个答案:

答案 0 :(得分:0)

这是我可以简化的最远的。 过滤器摆脱了if。 reduce去掉了for和returnObj变量;

return Object.keys(model)
        .filter(key => key in transFormObj)
        .reduce((rObj, key) =>
        {
            let newKey = transFormObj[key].newKey;
            if(isObject(newKey)) {
                let parentKey =  newKey.parentKey;
                let childKey = newKey.childKey;
                rObj[parentKey] = rObj[parentKey] || {};
                rObj[parentKey][childKey] = transFormObj[key].value(model);
            } else {
                rObj[newKey] = transFormObj[key].value(model);
            }
            return rObj;
        }, {}
        );