如何在AngularJS中保存对象的JSON索引位置,而不是对象本身

How to save a JSON index position of object, but not the object itself in AngularJS?

本文关键字:对象 位置 索引 JSON AngularJS 保存      更新时间:2023-09-26

这是我的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)中的那个对象呢?

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

如果你想基于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=>对象的散列。