繁体   English   中英

在Javascript对象中查找数据

[英]Finding data in Javascript Object

我有一个通过数据库调用创建的javascript对象。 它将有多个项目,我将需要能够通过特定的键/值(模块ID)来引用一个项目。

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();
        });
    }
});

不必遍历每个人来查找我要寻找的东西,有没有一种方法可以通过moduleID命名该对象,因为它具有唯一性?

例如,如果我想查看与moduleId 1有关的所有数据,我希望能够仅按ID搜索对象,而不是循环查找该对象。

我可以在创作中实现这一目标吗?

在此处输入图片说明

也许您需要的更像是:

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

这样,您就可以直接从ID请求特定模块。

您可以使用filter()函数搜索对象。

w3schools中的文档。

示例:按对象ID过滤

function matchId(id) {
    return moduleData.moduleID == id;
}

data = moduleData.filter(matchId);

这比用forforeach编写循环要简单得多。

祝好运并玩得开心点!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM