Possible Duplicate:
Merging Values into an Array
Asked
Active
Viewed 322 times
1
-
duplicate! http://stackoverflow.com/questions/610406/javascript-printf-string-format – Andrew Jackman Apr 06 '11 at 15:48
-
1Does this have anything to do with this: http://stackoverflow.com/questions/5568998/merging-values-into-an-array? – gen_Eric Apr 06 '11 at 15:49
3 Answers
4
Do you have control over the names of these variables? If so, I would change their structure like so:
var names = {
AppointmentSearchDays: 'aaa',
AppointmentSearchDaysBefore: 'bbb',
PrimeSuiteId: 'ccc'
};
var values = {
AppointmentSearchDays: 3333,
AppointmentSearchDaysBefore: 5,
PrimeSuiteId: 10
};
This would allow you to merge them like so:
var arr = [];
for (var key in names) {
if (names.hasOwnProperty(key)) {
arr.push(names[key] + ' ' + values[key]);
}
}
arr.join(',');
If you wanted to get real bold, you could do this:
var values = {
AppointmentSearchDays: { key: 'aaa', value: 3333 },
AppointmentSearchDaysBefore: { key: 'bbb', value: 5 }
PrimeSuiteId: { key: 'ccc', value: 10 }
};
var arr = [];
for (var i = 0, len = values.length; i < len; i++) {
arr.push(values[i].key + ' ' + values[i].value);
}
arr.join(',');

Eli
- 17,397
- 4
- 36
- 49
-
1+1 I was just typing the same thing :-) you can call var result = arr.join(); //comma is the default delimiter – SavoryBytes Apr 06 '11 at 15:54
-
2
I may be over simplifying the question, but just use the native concatenation operator +
.
var format = var AppointmentSearchDaysAfter
+ ' '
+ AppointmentSearchDaysAfterValue
+ ','
+ AppointmentSearchDaysBefore
+ ' '
+ AppointmentSearchDaysBeforeValue
+ ','
+ PrimeSuiteId
+ ' '
+ PrimeSuiteIdValue
alert(format);

Jason McCreary
- 71,546
- 23
- 135
- 174
1
You would just append all of the values using the '+' operator:
Actual String :
var result = AppointmentSearchDaysAfter + " " + AppointmentSearchDaysAfterValue + "," +AppointmentSearchDaysBefore + " " + AppointmentSearchDaysBeforeValue + "," + PrimeSuiteId + " " + PrimeSuiteIdValue;
Readible String :
var result = AppointmentSearchDaysAfter + " " +
AppointmentSearchDaysAfterValue + "," +
AppointmentSearchDaysBefore + " " +
AppointmentSearchDaysBeforeValue + "," +
PrimeSuiteId + " " +
PrimeSuiteIdValue;

Rion Williams
- 74,820
- 37
- 200
- 327