How can I highlight array elements 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 any way to simplify this with lodash?

+6
source share
3 answers

I do not understand what you are trying to sort out and what you expect in the end. For example, a way to write code in a question, this line will throw an error:

 answers[index].answerUid = element.answerUid; 

because it will read answers[index] from the answers object, get undefined and try to access the answerUid field of answerUid value.

Anyway, I can cover the main cases. If you want answers be an array, this would do this:

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

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

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

The _.pick function selects two answerUid and response fields from this field.

If $scope.question.answers is a key / value mapping, and you want to get the appropriate mapping in answers , then this would do this:

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

All solutions here have been tested, but it is possible that I entered a typo in the transcription.

+13
source

No need to use lodash, the native reduce works just as well - assuming the answers are a direct array (it looks like you're using 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 this is confusing, here is another example of using shorthand to sum an array of numbers:

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

The zero at the end is the initial value passed to the callback (as indicated above), and the value you return is passed to the next function call. Keep coming back, filter the functions inside and out of your body. You can reduce back any structure that you like, and not just simple primitive values.

edit: it looks like you assigned keys to an object with numerical values ​​- if you need an object, not an array, then it will be a little different.

0
source

You also need to wrap the function inside unary ( docs ). Otherwise, you pass the key and collection from iteratee to the pick ( docs ) function, and it may (should not) produce unexpected results.

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

All Articles