连接 2 个 JavaScript 数组
我有 2 个对象数组:用户和渠道。每个用户可以在多个频道中。每个频道可以包含许多用户。
频道对象示例:
{name: "test", visible: true, active: true}
用户对象示例:
{name: "user", ip: '127.0.0.1', sex: 1}
脚本必须执行以下操作:
- 按频道显示用户列表。
- 按用户显示频道列表。
- 所有基本操作(添加/删除/更新用户/频道);
实现这些对象之间的链接的更好方法是什么:
- 用户将包含他的频道列表。
- 频道将包含他的用户列表。
- 创建包含 user=channel 关联的单独对象。
- 或者你的变体...
我认为第三个变体会更好。
I have 2 arrays of objects: users and channels. Each user can be in many channels. Each channel can contain many users.
Channel object example:
{name: "test", visible: true, active: true}
User object example:
{name: "user", ip: '127.0.0.1', sex: 1}
Script must do such actions:
- Display users list by channel.
- Display channels list by user.
- All basic actions (add/remove/update user/channel);
What will be the better way to implement linking between these objects:
- User will contain his channels list.
- Channel will contain his users list.
- Create separate object which will contain user=channel assosiations.
- Or your variant...
I think that third variant will be better.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如您所知,有很多方法可以做到这一点,而哪种方法最终更多地取决于您将如何使用、访问和存储数据,而不是您向我们披露的数据。但是,这里有一种可行的方法:
为用户创建一个对象:
然后,您可以拥有一个用户对象数组,其中每个用户对象包含有关用户的基本信息并包含频道列表。这种数据结构选择经过优化,可以轻松了解用户属于哪个频道。
此结构并未针对了解哪些用户位于给定频道中进行优化。如果您想要从此数据结构中获得该信息,您仍然可以计算它,但这需要查看每个用户对象以找出给定频道中的用户。这是可行的,但速度不快。
如果您需要快速获得两种类型的信息(用户所在的频道以及频道中的哪些用户),那么您可能需要双重维护两个数据结构,一个为您提供每个答案。如果您通过方法或辅助函数对通道进行所有操作,那么它们都可以自动维护。
选择最终取决于您最需要如何访问数据以及哪种类型的访问必须速度快。由于您尚未分享该信息,因此我们无法确定哪个更好。
As you are aware, there are many ways to do this and which way ultimately depends more on how you're going to use, access and store the data than you have disclosed to us. But, here's one way that could work:
Create an object for a user:
Then, you can have an array of user objects, where each user object contains the basic information about the user and contains the list of channels. This data structure choice optimized for being able to easily know which channels a user belongs to.
This structure does not optimize for knowing which users are in a given channel. If you wanted that information from this data structure, you could still calculate it, but it would involve looking in every user object to find out which users were in a given channel. It's doable, but not fast.
If you need both types of information (which channels a user is in and which users are in a channel) available fast, then you may need to double maintain two data structures, one that gives you each answer. If you do all manipulation of the channels via methods or helper functions, then they can both be maintained automatically.
The choice ultimately depends upon how you most need to access the data and which types of access must be fast. Since you haven't shared that info, we can't really say which would be better.