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 ?
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.
Use forEach() to find an element in an array The Array. prototype. forEach() method executes the same code for each element of an array.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With