How to dynamically name my object params in this lodash loop?

493 Views Asked by At

https://lodash.com/docs#find

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?

2

There are 2 best solutions below

0
On BEST ANSWER

You're referring to params.term as an existing array, which is why you're getting an error. Try this instead...

params["term" + index] = ....

That will create a property for each index instead. You can either access it with

params["term1"]

or...

params.term1
1
On

You are trying to set params.term[1], params.term[2], and params.term[3]. This would work if params.term were an array, but it seems that in fact, params.term doesn't exist.

You said you want to set params.term1, params.term2, and params.term3, so you should do instead the following to programmatically access to the fields term1, term2 and term3.

params["term" + index] = _.result(_.find(n.tags, function(term_id) {
    return term_id;
}), 'term_id');