Javascript,简化对象转换

时间:2015-03-26 16:09:28

标签: javascript underscore.js

所以我有一个函数,它接受一个对象并将其转换为(略微)不同的对象。我做了第一次尝试让它工作,现在我想简化这个功能,我觉得我可以减少一点但是可以使用一些帮助。

所以对象就像这样传递

 {"module1":{"calender":["yes","no","maybe"]}}

并像这样吐出来

 {module1: "calender,yes,no,maybe"}

所以这就是我现在所拥有的:

 function(obj) {

                for (i in obj) {

                    for (p in obj[i]) {
                        var decodeModule = encodeURIComponent(decodeURIComponent(i));
                        var newObj = {};
                        var frontOf = encodeURIComponent(p);
                        var backOf = ""
                            //needs work
                        var lastItem = obj[i][p][obj[i][p].length - 1];
                        for (y in obj[i][p]) {

                            if (obj[i][p][y] == lastItem) {
                                //replace "," in last item
                                backOf += encodeURIComponent(decodeURIComponent(obj[i][p][y]));
                            } else {
                                backOf += encodeURIComponent(decodeURIComponent(obj[i][p][y])) + ",";
                            }
                        };
                        newObj[decodeModule] = frontOf + "," + backOf;
                    }
                }
                return newObj;
            }

所以我已经知道我不需要循环第二个循环(for(p in obj [i]))因为该级别总是只有1个项目。除此之外,我有点坚持如何清理这一点 - 有人建议我检查.reduce或.map使用更少的代码?我也在我的代码中使用下划线,如果它在这里会有所帮助。如果有人可以帮我把它变得更优雅,那就太爱了。谢谢阅读!

2 个答案:

答案 0 :(得分:2)

好的,这是一项有趣的练习。在我完成它后,我就像“为什么我们再这样做?” :)

我将属性值减少为字符串,然后使用正则表达式和_.map替换每个匹配项进行替换。 http://codepen.io/anon/pen/VYgodo

我知道这也可以改进。请有人把它拆开!!

var input = {
"module1": {
"calender": ["yes", "no", "maybe"]
},
"module2": {
"falender": ["yes", "no", "jein"]
}
};

//output: {module1: "calender,yes,no,maybe"}

function reduceObj(obj) {
newObj = {};


_.each(obj, function (value, key, list) {

var r = new RegExp(/(?:^({).*(:\[).*(\]})$)/);
//reduce property value to string and replace using regex
newObj[key] = JSON.stringify(list[key]).replace(r, function (match, p1, p2,    p3, p4, p5, offset, string) {
//this may be the only way to replace each capture
_.map([p1, p2, p3, p4], function (value, index, list) {
match = match.replace(value, "");
}); //end map

//replace double quote with comma and single quote with nothing
return match.replace(/\"\"/g, ',').replace(/\"/g, "");

}); //end replace


}); //end each

return newObj;
};

$(document).ready(function () {
console.log(reduceObj(input));
$('#output').html(JSON.stringify(reduceObj(input)));

});

答案 1 :(得分:1)

这样的事情怎么样?没有下划线,没有正则表达式,只是好老的香草JavaScript。

var input = {
  1: {
    "calender": ["yes", "no", "maybe"]
  },
  "module2": {
    "test2": ["|", "#", "&", "?", ",", "+", " ", "\\", "\""]
  },
  "One More for Good Measure": {}
};

function reduceObj(obj) {
  function helper(o) {
    var key = Object.keys(o)[0];
    if (typeof key != 'string') return '';
    return [].concat(key, o[key]).map(e_d).join(',');
  }

  function e_d(str) {
    return encodeURIComponent(decodeURIComponent(str));
  }
  
  var newObj = {}, prop;

  for (prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      newObj[e_d(prop)] = helper(obj[prop]);
    }
  }
  return newObj;
}

var output = reduceObj(input);
document.write('<pre>' + JSON.stringify(output, 0, 2));

如果module2下有多个密钥(例如),您需要做的就是更改helperDEMO

function helper(o) {
  var arr = [];   
  Object.keys(o).forEach(function(key) {
      o[key].unshift(key);
      arr = arr.concat(o[key]);
  });
  return arr.map(e_d).join(',');
}