json回参考 [英] json back reference

查看:138
本文介绍了json回参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个分层的json对象,我想遍历它,并将父节点附加到每个元素。这就是我所做的

  function attach_back_reference(hierarchy,parent){
hierarchy.parent = parent;
for(var i in hierarchy){
if(jQuery.isPlainObject(hierarchy [i]))
attach_back_reference(hierarchy [i],hierarchy);
}
}

但这是给出错误。 超过最大调用堆栈大小

解决方案

自从你

  for(var i in hierarchy){

添加属性后,一个值 i 将为父母,所以你最终可以无限制地将孩子设为自己的祖父母。



你可以在

  var o = {}; 
o.x = o;
(var i in o){alert(i);

哪些提醒x / p>

将循环移动到顶部。

  function attach_back_reference(hierarchy,父代){
for(var i in hierarchy){
if(jQuery.isPlainObject(hierarchy [i]))
attach_back_reference(hierarchy [i],hierarchy);
}
hierarchy.parent = parent;
}

或者,如果您只需要这样来处理较新的口译员,就可以尝试使父属性无可争辩: javascript defineProperty使属性不可枚举


I've a hierarchical json object, I want to traverse it and attach a parent node to each element. This is what I've done

function attach_back_reference(hierarchy, parent){
    hierarchy.parent = parent;
    for(var i in hierarchy){
        if(jQuery.isPlainObject(hierarchy[i]))
            attach_back_reference(hierarchy[i], hierarchy);
    }
}

But this is giving error. Maximum call stack size exceeded

解决方案

Since you do

for(var i in hierarchy){

after adding the parent property, one value of i will be "parent", so you end up setting the child as its own grandparent infinitely.

You can see this in

var o = {};
o.x = o;
for (var i in o) { alert(i); }

which alerts "x".

Move the loop to the top.

function attach_back_reference(hierarchy, parent){
    for(var i in hierarchy){
        if(jQuery.isPlainObject(hierarchy[i]))
            attach_back_reference(hierarchy[i], hierarchy);
    }
    hierarchy.parent = parent;
}

Alternatively, if you only need this to work on newer interpreters, you can try making the parent property unenumerable : javascript defineProperty to make an attribute non enumerable

这篇关于json回参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆