[英]Making a subset of an array of JavaScript objects based on one of their properties?
I have a JavaScript array of objects with the same properties each, something like this: 我有一个对象的JavaScript数组,每个对象具有相同的属性,如下所示:
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. 我想对该数组进行子集处理,以使其仅包含与名称“列表”匹配的对象,然后将不包含这些对象的对象复制到另一个名为
cache
数组中。 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. 我在想,也许我可以将对象数组与另一个数组进行比较,该数组仅包含具有要匹配的所需名称的字符串列表,对照该列表检查每个对象的name属性,以创建一个具有匹配名称的新数组。 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.
也许将200-500个对象中的每个对象与具有100个名称的列表进行比较并不是一件好事,我真的不知道。
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.
遍历box对象中的每个项目,如果其中包含列表中的名称,则将其包括在内。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.