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.