如何实现两个数组之间的双向连接?

How to implement bi-directional connection between two arrays?

在我的应用程序中,我有一个 ItemsService,它从服务器获取项目并将它们作为 JSON 对象存储在其 cache 变量中。物品可以出现在许多地方,例如在 table 或 graph/chart 等。

例如,当我初始化一个 table - 我只需要从 cache 中选择特定的项目,例如第一,第三,第七。

如何实现它们之间的双向连接?基本上我希望 table 包含对 cache 中特定项目的引用,所以当我在 cachetable 中更改项目时 - 它的状态将始终同步因为它是相同的项。

另外,当我从 table 中删除项目时 - 它需要从 cache 中删除。

这是 tablecache 结构的示例:

Table:

table: {
    "36": { // it's a name of a row
        "72": [items], // it's a name of a column with corresponding items
        "73": [items],
        "74": [items]
    },

    "37": {
        "72": [],
        "73": [items],
        "74": [items]
    },
    "38": {
        "72": [],
        "73": [],
        "74": []
    }
}

ItemsService 缓存(简化版):

ItemsService = {
  cache: [items]
};

项目结构:

{
  id: 3,
  parent_id: 1, 
  name: 'First Item', 
  siblings: [1,2,3],
  active_users: [{user_id: 1, avatar_url: 'http://...'}, ...],
  // 50 more fields :)
}

还需要指出的是,我使用 angular-ui-sortable 插件允许在 columns/rows 之间拖动项目,我需要为 ng-model 提供数组(我认为)。这是现在的样子:

<td ui-sortable="vm.sortableOptions"
    ng-model="vm.table[row.id][column.id]">
  <sb-item itemid={{item.id}} 
           ng-repeat="item in vm.table[row.id][column.id]">
  </sb-item>
</td>

最好的选择是对象。在 javascript 中保存对象的变量并不是真正保存对象,而是对所述对象的引用。当您将该变量传递给另一个变量时,引用值会被复制,因此两个变量都指向同一个对象。

var a = { 0: 'Property 0' };
var b = a;
b[0] = 'Property 0!'; //a[0] also the same.
delete b[0]; //a[0] nor b[0] exist anymore.

除非出于某种原因必须使用两个 单独的 数组,否则您是否考虑过使用 filter?

使用对象(而不是 JSON)会起作用。

那么您的缓存和 table 都指向相同的项目对象。如果您更改对象中的某些内容,它会反映在两端。

var cacheArray = [{ item: 1 }, { item: 2}];  
table[0][0] = cacheArray[0];  
console.log(table[0][0].item);  // 1 
cacheArray[0].item = 9;  
console.log(table[0][0].item);  // 9.  

请注意数组和table没有改变。他们仍然指向相同的对象。