Reputation: 8970
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?
Upvotes: 0
Views: 60
Reputation: 463
You can use filter()
function for searching object.
Document in w3schools.
Example: Filter by object ID
function matchId(id) {
return moduleData.moduleID == id;
}
data = moduleData.filter(matchId);
It is more simple than you write a loop with for
or foreach
.
Goodluck and have fun!
Upvotes: 0
Reputation: 709
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.
Upvotes: 1