我有一个函数,它可以将一个对象转换为(略有不同的)另一个对象。我先写了一个初版,只是为了让它能够工作,现在我想简化这个函数,感觉可以删减一些代码,但需要一些帮助。
所以对象是这样传入的
{"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来使用更少的代码? 我还在我的代码中使用了underscore,如果可以的话,这里会有所帮助。 如果有人能帮我使这个代码变得更加优美,那就太好了。 谢谢阅读!