【问题标题】:How to save a JSON index position of object, but not the object itself in AngularJS?如何在AngularJS中保存对象的JSON索引位置,而不是对象本身?
【发布时间】:2014-09-18 14:43:58
【问题描述】:

这是我的 JSON:

$scope.myjson = [
                   {id: "1", name: "a"},
                   {id: "2", name: "b"},
                   {id: "3", name: "c", children: [{id: "4", name: "d"}]}
               ];

我想在javascript中保存对象X的位置,例如第一个对象的位置是$scope.myjson[0],但我不想保存对象本身,我只想要位置。以同样的方式我想保存$scope.myjson[2].children[0]

我必须将其保存为字符串吗? 我如何使用它在 O(1) 中获取该对象?

【问题讨论】:

  • 你到底在说什么?
  • 你想把它保存在哪里?你怎么知道哪个对象需要保存?
  • 我正在使用 foreach 遍历 json 并寻找特定的 id。我想将该对象位置保存在 json 中,所以稍后我可以真正在 O(1) 中获取对象,而无需再次搜索我的所有 json。
  • 我的对象位置可以是:$scope.myjson[1].children[0].children[1].children[4].children[0]
  • 你想把它保存在哪里?

标签: javascript arrays angularjs arraylist


【解决方案1】:

为什么要保存对象的位置而不仅仅是对象本身?

如果您希望基于 id 查找来缓存对象,这样的方法会起作用(完全未经测试):

var find = (function() {
    var cache = {}, fn; 

    return fn = function(/*array*/ arr, id) {
       if(cache[id]) return cache[id];
       for(var i=0; i < arr.length; i++) {
          if(arr[i].id === id) 
             return (cache[id] = arr[i]);
          if(arr[i].children && val = fn(arr[i].children, id)) 
             return (cache[id] = val);
       }

       return null;
    }
})();

这样后续对 find 的调用将返回缓存的对象。根据数组的大小和查找频率,您也可以只对其进行一次迭代并创建一个 id => object 的哈希。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 2020-09-12
    • 2011-06-14
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2018-09-21
    相关资源
    最近更新 更多