I have a function which needs to return either an array or object. I'm not sure which is best and I'm not sure how to construct it. Here's what I have so far. Pay close attention to the comments in ALL CAPS. The idea is to loop through a set of td cells that contain a 'data-field' attribute, and use the name of the attribute as the variable name and the text contained within the td as the value. The number of properties or values of the array/object are unknown. Depending on what was clicked to enter into the function, 2-6 values will be needed.
function InlineEditMode(rowID, entryType) {
// store current row data in case of cancel
var original = $('#'+rowID).contents();
// DEFINE SOME ARRAY OR OBJECT HERE
// put original values in the newEntry Array with a loop, using the
// data-field attributes as the name of the array or object variables
// and the text of the td as the value
$('#'+rowID+' td[data-field]').each(function() {
var field = $(this).attr('data-field');
var value = $(this).text();
// BUILD OUT OBJECT OR ARRAY
});
// RETURN ARRAY OR OBJECT
}
-
Sounds like you need a hashmap/associative arrayMike Tunnicliffe– Mike Tunnicliffe2011年02月03日 20:52:35 +00:00Commented Feb 3, 2011 at 20:52
2 Answers 2
I believe something like this would work for your purposes.
function InlineEditMode(rowID, entryType) {
// store current row data in case of cancel
var original = $('#'+rowID).contents();
// DEFINE SOME ARRAY OR OBJECT HERE
var buildup = {};
// put original values in the newEntry Array with a loop, using the
// data-field attributes as the name of the array or object variables
// and the text of the td as the value
$('#'+rowID+' td[data-field]').each(function() {
var field = $(this).attr('data-field');
var value = $(this).text();
// BUILD OUT OBJECT OR ARRAY
buildup[field] = value;
});
// RETURN ARRAY OR OBJECT
return buildup;
}
7 Comments
buildup.field = value which wasn't workingTry this:
function InlineEditMode(rowID, entryType) {
// store current row data in case of cancel
var original = $('#'+rowID).contents();
var toReturn = {};
// DEFINE SOME ARRAY OR OBJECT HERE
// put original values in the newEntry Array with a loop, using the
// data-field attributes as the name of the array or object variables
// and the text of the td as the value
$('#'+rowID+' td[data-field]').each(function() {
var field = $(this).attr('data-field');
var value = $(this).text();
toReturn[field] = value;
});
// RETURN ARRAY OR OBJECT
return toReturn;
}