Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 313
Samantha J T Star Avatar asked Feb 07 '14 19:02

Samantha J T Star


People also ask

How do you find the specific element of an array?

get() is an inbuilt method in Java and is used to return the element at a given index from the specified Array. Parameters : This method accepts two mandatory parameters: array: The object array whose index is to be returned.

How do I find an element in an array of arrays?

Use forEach() to find an element in an array The Array. prototype. forEach() method executes the same code for each element of an array.

How can we get values from object using Lodash?

get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.

How do you filter an array of objects?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


1 Answers

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 answers object, get undefined and try to access the field answerUid of the undefined value.

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

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

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

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

The _.pick function picks the two fields answerUid and response out of the object.

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

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.

like image 191
Louis Avatar answered Sep 21 '22 04:09

Louis