Reputation: 367
I am trying to populate the following string if I have n data:
group.items[0].fname || group.items[1].fname ||..........|| group.items[n].fname
I have implemented following, I would like to know is there a better way to do that?
nam="";
for (i = 0; i < data.length; i++) {
if(i==0)
nam="groups.items["+i+"]"+".fname";
else
nam=nam+"||"+"group.items["+i+"]"+".fname";
}
Upvotes: 0
Views: 58
Reputation: 193261
Since data
is an array you can simply use Array.prototype.map
to build array of substrings and then join them:
var data = [1,2,3];
var nam = data.map(function(el, i) {
return 'group.items[' + i + '].fname';
}).join('||');
alert(nam);
Upvotes: 1