如何用lodash挑选数组的元素?

Sam*_*tar 6 javascript lodash

我有这个代码:

        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;
        });
Run Code Online (Sandbox Code Playgroud)

有什么方法可以使用lodash简化这个吗?

Lou*_*uis 13

我不清楚你想要迭代什么,以及你期望在最后得到什么.例如,当前编写问题代码的方式,此行将导致错误:

answers[index].answerUid = element.answerUid;
Run Code Online (Sandbox Code Playgroud)

因为它将answers[index]answers对象中读取,获取undefined并尝试访问answerUidundefined值的字段.

无论如何,我可以涵盖重大案件.如果你想answers成为一个数组,那么这样做:

var answers = _.map($scope.question.answers,
                    _.partialRight(_.pick, "answerUid", "response"));
Run Code Online (Sandbox Code Playgroud)

这适用$scope.question.answers于数组还是数组Object.该_.partialRight(_.pick, "answerUid", "response"))电话相当于:

function (x) {
    return _.pick(x, ["answerUid", "response"]);
}
Run Code Online (Sandbox Code Playgroud)

_.pick函数选择两个字段answerUidresponse从对象中取出.

如果$scope.question.answers是键/值映射,并且您想要相应的映射answers,那么这样做:

var answers = _.mapValues($scope.question.answers,
                          _.partialRight(_.pick, "answerUid", "response"));
Run Code Online (Sandbox Code Playgroud)

这里的所有解决方案都经过测试,但我在转录中引入了一个错字并非不可能.