我如何指数多个项目在Array或使用JavaScript / jQuery对象?多个、对象、指数、项目

2023-09-10 19:12:08 作者:烟雨江南

我有数据,通过Ajax调用返回的结果对象数组。数据是这样的:

I have an Array of data in a result object returned by an Ajax call. The data looks like this:

{ Name="User1 Name1", FirstName="User1", Id="005400000001234567", more...}
{ Name="User2 Name1", FirstName="User2", Id="005400000001234568", more...}

,其中每个项目看起来是这样的:

Where each item looks like this:

{
    Id:"005400000001234567",
    Name:"User Name",
    FirstName:"User",
    LastName:"Name",
    Title:"Manager"
}

问题

我希望能够或者通过编号(返回单个用户)或标题(老用户的数组)来检索数据。什么是去这样做的最好办法是使用JavaScript的或的jQuery的?

Question

I want to be able to retrieve data either by Id (returning a single user) or by Title (returning an array of users). What would be the best way to go about doing that using JavaScript or jQuery?

下面是我到目前为止已经尝试:

Here's what I've attempted so far:

function GetAllUsers()
{
    AllUsersById = new Object();

    MyClass.MyAjaxMethod(function(result,event) {
        if(result) { 
            j$(result).each(function(index,item)
            {
                AllUsersById[item.Id] = item;
            });
        }
    });
}

在code我上面是伟大的索引凭身份证,但我不知道该怎么做了标题。

The code I have above is great for indexing by Id, but I'm not sure what to do for Title.

另外,顺便说一下,大约有 1000条记录,然后我需要这是的相当有效的。 (这是我得到的数据马上的原因之一,当文档准备好了。我不是的JavaScript或jQuery的效率方面的专家,但让我知道,如果你有一个更好的办法。)

Also, by the way, there are about 1000 records, and I need this to be fairly efficient. (This is one of the reasons I'm getting the data right away, when the document is ready. I'm not an expert on JavaScript or jQuery efficiency, though. Let me know if you have a better way.)

任何想法?在此先感谢!

Any ideas? Thanks in advance!

推荐答案

好像你正在寻找 .grep()。使用.grep你可以创建一个通用的函数,将过滤器:

Seems like you're looking for .grep(). Using .grep you could create a generic function that would filter:

function findInJson (json, key, value) {
    return $.grep(json, function (obj) {
        return obj[key] == value;
    });
}

// With your data getting a specific user by id
findInJson(yourJSON, "Id", "005400000001234567");

// Getting a set of users by title
findInJson(yourJSON, "Title", "Manager");