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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21636343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:23:15  来源:igfitidea点击:

How can I pick out elements of an array with lodash?

javascriptlodash

提问by Samantha J T Star

I have this code:

我有这个代码:

        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;
        });

Is there some way that I could simplify this using lodash ?

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

回答by Louis

It is unclear to my what it is you are trying to iterate over and what it is you expect to have at the end. For instance, the way the code in the question is currently written, this line will cause an error:

我不清楚您要迭代的是什么,以及您希望最终得到什么。例如,问题中的代码当前的编写方式,此行将导致错误:

answers[index].answerUid = element.answerUid;

because it will read answers[index]from the answersobject, get undefinedand try to access the field answerUidof the undefinedvalue.

因为它会读取answers[index]answers对象,获得undefined并尝试接入领域answerUid中的undefined价值。

At any rate, I can cover the major cases. If you want answersto be an array, then this would do it:

无论如何,我可以涵盖主要情况。如果你想answers成为一个数组,那么可以这样做:

var answers = _.map($scope.question.answers,
                    _.partialRight(_.pick, "answerUid", "response"));

This works whether $scope.question.answersis an array or an Object. The _.partialRight(_.pick, "answerUid", "response"))call is equivalent to:

无论$scope.question.answers是数组还是Object. 该_.partialRight(_.pick, "answerUid", "response"))调用相当于:

function (x) {
    return _.pick(x, ["answerUid", "response"]);
}

The _.pickfunction picks the two fields answerUidand responseout of the object.

_.pick函数挑选两个字段answerUidresponse出的对象。

If $scope.question.answersis a key/value mapping and you want a correponding mapping in answers, then this would do it:

如果$scope.question.answers是键/值映射,并且您希望在 中进行相应的映射answers,则可以这样做:

var answers = _.mapValues($scope.question.answers,
                          _.partialRight(_.pick, "answerUid", "response"));

All the solutions here have been tested but it is not impossible that I introduced a typo in transcription.

这里的所有解决方案都已经过测试,但我在转录中引入了拼写错误并非不可能。

回答by dmp

No need to use lodash, native reduceworks just as well - assuming that answers is a straight up array (looks like you are using angular?).

不需要使用 lodash,原生的reduce 也可以工作——假设答案是一个直接的数组(看起来你正在使用 angular?)。

 var answers = _.clone($scope.question.answers)
 var filteredAnswers = answers.reduce(function(working, current, index ){
     working.push({
        answerUid: current.answerUid,
        response: current.response
     });
     return working;
 },[]);

If that's confusing, here's another example of using reduce to sum an array of numbers:

如果这令人困惑,这里有另一个使用 reduce 对数字数组求和的示例:

[1,2,3].reduce(function(sum, current){return sum + current;},0); // 6

The zero at the end is the initial value passed into the callback (as sum above), and the value you return is passed on to the next call of the function. Keep returning, filter inside your function body, and away you go. Reduce can return whatever structure you like, not just single primitive values.

最后的零是传递给回调的初始值(如上面的总和),您返回的值将传递给函数的下一次调用。继续返回,在函数体内过滤,然后离开。Reduce 可以返回您喜欢的任何结构,而不仅仅是单个原始值。

edit: it looked like you were assigning keys on an object with numeric values - if you need an object as opposed to an array, then that would be a bit different.

编辑:看起来您正在为具有数值的对象分配键 - 如果您需要一个对象而不是数组,那会有点不同。

回答by SeregPie

You also need to wrap the function inside unary(docs). Otherwise you pass the key and the collection from iteratee to the pickfunction (docs) and it can (must not) lead to unexpected results.

您还需要将函数包装在unary( docs) 中。否则,您将 key 和集合从 iteratee 传递给pick函数(docs),它可能(不得)导致意外结果。

var answers = _.mapValues($scope.question.answers, _.unary(_.partialRight(_.pick, 'answerUid', 'response')));