Reputation: 15555
var student = [{
"fname": "Jackie",
"mname": "Lee",
"lname": "Li"
}, {
"fname": "Ken",
"mname": "Ryu",
"lname": "Sha"
}];
for (var i = 0; i < student.length; i++) {
console.log(student[i].fname + " " + student[i].mname + ". " + student[i].lname ? student[i].fname + " " + student[i].mname + ". " + student[i].lname + " , " : " ");
}
I am trying to combine names in the a td
these names are from an array. I was able to make the names combine by above code. problem is on the last name there is still a ,
just want to get rid of the comma when there are no more names that will follow. I am bugged by this simple comma for hours. any idea is appreaciate.
Upvotes: 1
Views: 84
Reputation: 157
If I understand your question right than this should do it:
for(var i = 0 ; i < student.length; i++){
var name = student[i].fname + " " + student[i].mname + ". " + student[i].lname ? student[i].fname + " " + student[i].mname + ". " + student[i].lname: " ";
if (i < (student.length - 1)) {
name += ',';
}
}
Upvotes: 3
Reputation: 4458
Try this bit of code
var student = [{
"fname": "Jackie",
"mname": "Lee",
"lname": "Li"
}, {
"fname": "Ken",
"mname": "Ryu",
"lname": "Sha"
}]
for (var i = 0; i < student.length; i++) {
var out = student[i].fname + " " + student[i].mname + ". " + student[i].lname;
if (i < student.length - 1) {
out += ", ";
} else {
out += " ";
}
snippet.log(out);
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Upvotes: 3
Reputation: 1074266
One easy way is to build up an array and then using .join(", ")
:
var student = [{
"fname": "Jackie",
"mname": "Lee",
"lname": "Li"
}, {
"fname": "Ken",
"mname": "Ryu",
"lname": "Sha"
}];
var names = [];
for (var i = 0; i < student.length; i++) {
names.push(student[i].fname + " " + student[i].mname + ". " + student[i].lname);
}
snippet.log(names.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
It can even be more concise with Array#map
:
var student = [{
"fname": "Jackie",
"mname": "Lee",
"lname": "Li"
}, {
"fname": "Ken",
"mname": "Ryu",
"lname": "Sha"
}];
snippet.log(student.map(function(entry) {
return entry.fname + " " + entry.mname + ". " + entry.lname;
}).join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Upvotes: 6
Reputation: 2321
Try this jsfiddle
you should use like this:
var student = [{
"fname": "Jackie",
"mname": "Lee",
"lname": "Li"
}, {
"fname": "Ken",
"mname": "Ryu",
"lname": "Sha"
}]
for (var i = 0; i < student.length; i++) {
console.log(student[i].fname + " " + student[i].mname + ". " + student[i].lname + ((i < student.length - 1) ? ", " : " "));
}
Upvotes: 2