简体   繁体   English

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

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

Here is my JSON: 这是我的JSON:

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

I want to save in javascript the position of object X, for example the position of first object is $scope.myjson[0] , but I don't want to save the object itself, I just want the position. 我想在javascript中保存对象X的位置,例如,第一个对象的位置是$scope.myjson[0] ,但是我不想保存对象本身,我只想保存位置。 On the same way I want to save $scope.myjson[2].children[0] . 以同样的方式,我想保存$scope.myjson[2].children[0]

I must save it a string? 我必须保存一个字符串吗? How than I use it to get that object in O(1)? 比起我如何用它在O(1)中获得那个对象呢?

Why do you want to save the position of the object and not simply the object itself? 为什么要保存对象的位置,而不仅仅是对象本身?

If you're looking to cache objects based on an id lookup something like this would work (completely untested): 如果您要基于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;
    }
})();

This way subsequent calls to find would return the cached object. 这样,随后的find调用将返回缓存的对象。 Depending on the size of the array and the frequency of lookups, you could also just iterate over it once and create a hash of id => object. 根据数组的大小和查找的频率,您还可以对其进行一次迭代并创建id => object的哈希。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM