根据 JavaScript 对象的属性之一创建 JavaScript 对象数组的子集?
我有一个 JavaScript 对象数组,每个对象都具有相同的属性,如下所示:
box[0] = { name: 'somename', /* more properties... */ };
box[1] = { name: 'othername', /* more properties... */ };
box[2] = { name: 'onemorename', /* more properties... */ };
// more objects in the array...
我想对这个数组进行子集化,以便它只包含与名称 “列表” 匹配的对象,并复制不匹配的对象可能是另一个名为 cache
的数组。我在想也许我可以将这个对象数组与另一个数组进行比较,另一个数组只包含一个字符串列表,其中包含要匹配的所需名称,对照此列表检查每个对象的名称属性,以创建一个包含匹配项的新数组。我不知道这是否有效,或者这是否是实现我想要的目标的最佳方法,这就是为什么我请求您的帮助。也许根据包含 100 个名称的列表检查 200-500 个对象中的每一个并不是一件好事,我真的不知道。
您对我如何做到这一点有什么想法吗?更好的是,你能给我举个例子吗?
提前致谢。
I have a JavaScript array of objects 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您想要的名称列表存储在一个数组中,
有两个数组 - 与名称匹配的数组和不匹配的数组。循环遍历框对象中的每个项目,如果它包含列表中的名称,则将其包含在内。
我希望有某种数组差异操作,所以你可以这样做(用伪代码):
Assuming the list of names you do want are stored in an array,
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.
I wish there was a array difference operation of some kind, so you could do (in pseudocode):