var params = {};
_.forEach(n.tags, function(n, index) {
console.log(index);
index++
// For each tag, create new param.term1, term2, term3 etc...
params.term[index] = _.result(_.find(n.tags, function(term_id) {
return term_id;
}), 'term_id');
});
The _.forEach
will loop over n.tags
(which contains up to 3 tags).
I iterate the index++
by 1 so I start with 1 not 0, to create "term1".
Now the next part is where I'm trying to dynamically generate up to 3 new params.term[i] values.
params.term[index] = _.result(_.find(n.tags, function(term_id) {
return term_id;
}), 'term_id');
What I'm trying to get is the following:
params.term1 = 111;
params.term2 = 222;
params.term3 = 333;
The error I'm currently getting is TypeError: Cannot set property '1' of undefined when I try to dynamically set the param name here: params.term[index]
How would you accomplish this using _lodash
?
You're referring to
params.term
as an existing array, which is why you're getting an error. Try this instead...That will create a property for each index instead. You can either access it with
or...