SBB SBB - 5 months ago 10
jQuery Question

Finding data in Javascript Object

I have a javascript object I am creating from a database call. It will have multiple items and I will need to be able to reference one by a specific key/value (moduleID).

success: function(data) {

// Define our local vars
var moduleIncludes = Array();

// Loop over each of the users selected modules and put them into an array
$(data).find('modules').each(function() {

// Push module JS file names to an array
moduleIncludes.push($(this).find('moduleJSFile').text());

// Create an object of module data
moduleData.push({
moduleID: $(this).find('moduleID').text(),
moduleRow: $(this).find('row').text(),
moduleColumn: $(this).find('col').text(),
moduleName: $(this).find('moduleName').text(),
moduleDescription: $(this).find('moduleDescription').text(),
moduleJSFile: $(this).find('moduleJSFile').text(),
moduleIcon: $(this).find('moduleIcon').text(),
moduleStartingXsize: $(this).find('startingXsize').text(),
moduleStartingYsize: $(this).find('startingYsize').text(),
moduleResizeLocked: $(this).find('resizeLocked').text(),
moduleMinXsize: $(this).find('minXsize').text(),
moduleMinYsize: $(this).find('minYsize').text()
});
});

// Using our array of modules, fetch them to include them into the page
$.getMultiScripts(moduleIncludes, 'includes/js/modules/').done(function() {
// All of the modules have been included. Trigger the grid functionality.
renderCanvas();
});
}
});


Instead of having to loop over each one to find what I am looking for, is there a way I can name the object by the
moduleID
instead since its unique?

For example, if I want to see all the data pertaining to moduleId 1, I would like to be able to just search the object by ID rather than loop it to find it.

Can I achieve this in my creation?

enter image description here

Answer

maybe what you need is more like:

moduleIncludes = {};
moduleIncludes[Id] = {"moduleRow":$(this).find('row').text() ...};

doing like this, you'll be able to request a specific module directly from ID.

Comments