【问题标题】:How to implement bi-directional connection between two arrays?如何实现两个数组之间的双向连接?
【发布时间】:2015-12-24 20:24:31
【问题描述】:

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

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

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

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

这是tablecache 结构的示例:

表:

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 插件来允许在列/行之间拖动项目,并且我需要为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>

【问题讨论】:

  • 你应该向我们展示两个数组的结构,因为有很多方法可以做到这一点,这将取决于它们的结构。
  • 我提供了结构
  • items 结构是最重要的。
  • 项目是一个复杂的对象。将在几分钟内提供它的示例。

标签: javascript angularjs jquery-ui-sortable angular-ui-sortable


【解决方案1】:

你最好的选择是对象。在 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.

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      然后你的缓存和你的表都指向相同的项目对象。如果您更改对象中的某些内容,它会在两端反映出来。

      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.  
      

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

      【讨论】:

        猜你喜欢
        • 2013-02-18
        • 2017-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-15
        • 1970-01-01
        • 2013-08-06
        • 1970-01-01
        相关资源
        最近更新 更多