动态创建和删除JavaScript关联数组键和值

时间:2011-09-06 12:02:58

标签: javascript jquery arrays associative-array

我正在使用jQuery 1.6

我在JavaScript方面不太好,我需要动态创建一个包含2个动态参数的数组:json.idjson.name

数组创建应该导致:

[

[json.id]
         [ 
           json.name,
             json.name,
              json.name,
                etc .....
         ]
[json.id]
          [
           json.name, 
             json.name,
               json.name,
                  etc ....
         ]
etc ...
]

然后我需要能够删除json.idjson.id json.name ....

有没有人可以通过所有浏览器的支持向我展示如何执行此操作?

THX [EDITED]

逻辑是这样的:(希望很清楚:P)

    //first ajax call result:
    [{json.id_parent:json.name,json.id_parent:json.name,json.id_parent:json.name, etc..}]

    //second ajax call results passing the json.id_parent:
    [{json.id_parent_child:json.name,json.id_parent_child:json.name,json.id_parent_child:json.name,etc...}]
    //now for each call = id_parent create an associative array: 

{ 
id_parent:{id_parent_child,id_parent_child,etc ....},
id_parent:{id_parent_child,id_parent_child,etc ....},
etc...
}

1 个答案:

答案 0 :(得分:1)

    var myJson = {'id39':{'name':'Jesus','age':33}};
    var idDel = 'id39';
    delete myJson[idDel];// delete the complete reference with id
    var propDel = 'name';
    delete myJson[idDel][propDel];// delete only the property 'name' of the reference with id
// parsing complete json
    $.each(myJson, function(key, obj){// parse objects
      if(condition){
        delete myJson[key];// delete reference
      }
      $.each(obj, function(propName, val){// parse properties
        if(condition){
          delete obj[propName];// delete property
        }
      }
    });

注意,此示例假设您使用json对象而不是数组,因此删除子对象或属性更容易,更快......