我有这个代码:
- var answers = _.clone($scope.question.answers)
- var answers = {};
- $scope.question.answers.forEach(function (element,index) {
- answers[index].answerUid = element.answerUid;
- answers[index].response = element.response;
- });
有什么方法可以使用lodash简化这个吗?
解决方法
我不清楚你想要迭代什么,以及你期望在最后得到什么.例如,当前编写问题代码的方式,此行将导致错误:
- answers[index].answerUid = element.answerUid;
因为它将从answers对象中读取答案[index],获取未定义并尝试访问未定义值的字段answerUid.
无论如何,我可以涵盖重大案件.如果你想要答案是一个数组,那么这样做:
- var answers = _.map($scope.question.answers,_.partialRight(_.pick,"answerUid","response"));
无论$scope.question.answers是数组还是Object,这都有效. _.partialRight(_.pick,“answerUid”,“response”))调用相当于:
- function (x) {
- return _.pick(x,["answerUid","response"]);
- }
_.pick函数从对象中选择两个字段answerUid和response.
如果$scope.question.answers是键/值映射,并且您希望在答案中有相应的映射,那么这样做:
- var answers = _.mapValues($scope.question.answers,"response"));
这里的所有解决方案都经过测试,但我在转录中引入了一个错字并非不可能.