I have a Javascript object, which contains other objects. Each of the contained objects has got a name property.
What I would like to do now is to concatenate these name properties to one String. However, I want these Strings separated by commas and an 'and' before the last String.
For better understanding, the object i want to iterate over would look like this:
var objects = {
o1: {name: 'name1'},
o2: {name: 'name2'},
o3: {name: 'name3'}
};
Now the String I would like to have in the end would be: 'Concatenation of name1, name2 and name3'
What I've tried so far was using angular.forEach:
var myString = 'Concatenation of ';
angular.forEach(objects, function(o) {
myString += o.name + ', ';
}
Not hard to notice, that my String would become 'Concatenation of name1, name2, name3, '.
So the real question would be how I can check at which position in my object I am and reacting appropiately by concatenating 'and' instead of a comma or no comma at all. How can I do that?
angular.forEach(objects, function(o,i,r) { ... if(r[i+1]) myString+=", ";but better is to domyString=angular.map(objects, function(o) { return o.name;}).join(", ");