Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
85
rated 0 times [  90] [ 5]  / answers: 1 / hits: 14990  / 9 Years ago, thu, september 24, 2015, 12:00:00

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?


More From » angularjs

 Answers
2

Use a traditional for loop:



var myString = 'Concatenation of ';
var i = 0;
var keys = Object.keys(objects);
for (i =0; i<keys.length; i++) {
if (i > 0)
myString += (i < keys.length - 1) ? ', ' : ' and ';
myString += objects[keys[i]].name;
}

[#33954] Wednesday, September 23, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
antonb

Total Points: 424
Total Questions: 104
Total Answers: 101

Location: Serbia
Member since Tue, Jul 26, 2022
2 Years ago
;