根据 JavaScript 对象的属性之一创建 JavaScript 对象数组的子集?

发布于 2024-10-15 12:31:24 字数 617 浏览 2 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

背叛残局 2024-10-22 12:31:24

假设您想要的名称列表存储在一个数组中,

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

有两个数组 - 与名称匹配的数组和不匹配的数组。循环遍历框对象中的每个项目,如果它包含列表中的名称,则将其包含在内。

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

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

我希望有某种数组差异操作,所以你可以这样做(用伪代码):

var cache = box - objectsMatchingName

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文