开发者

Making a subset of an array of JavaScript objects based on one of their properties?

I have a JavaScript array of object开发者_JAVA技巧s with the same properties each, something like this:

box[0] = { name: 'somename', /* more properties... */ };
box[1] = { name: 'othername', /* more properties... */ };
box[2] = { name: 'onemorename', /* more properties... */ };
// more objects in the array...

I want to subset this array so that it only contains objects that match a "list" of names and copy the ones that don't to another array named cache maybe. I was thinking maybe I could compare this array of objects to another array which just contains a list of strings with the desired names to match against, checking each object's name property against this list to create a new array with the ones that matched. I don't know if this would work or if it is the best approach to achieve what I want, that is why I am asking for your help. Maybe checking each of 200-500 objects against a list with 100 names is not a very good thing to do, I don't know really.

Do you have any ideas on how I could do this? even better, can you point me to an example?

Thanks in advance.


Assuming the list of names you do want are stored in an array,

var wantedNames = [ "first name", "second name", .. ];

have two arrays - those matching a name and those that don't. Loop through each item in the box object, and if it contains a name from the list, then include it.

var objectsMatchingName = box.filter(function(item) {
    return wantedNames.indexOf(item.name) !== -1;
});

var cache = box.filter(function(item) {
    return objectsMatchingName.indexOf(item) === -1;
});

I wish there was a array difference operation of some kind, so you could do (in pseudocode):

var cache = box - objectsMatchingName
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜