如何在JSON对象

时间:2015-06-11 08:26:21

标签: javascript json

这是我的目标:

{
    "title": "title",
    "Components": [{
        "title": "component 1",
        "id": 0,
        "contents": {
            "1": {
                "title": "sub-component 1",
                "sub_contents": {
                    "1": {
                        "title": "blah",
                    }
                }
            },
           "2": {
                "title": "sub-component 1",
                "sub_contents": {
                    "3": {
                        "title": "blah",
                    }
                }
            }
        }
    }]
} 

sub_contents对象中的对象每个都以一个数字属性开头。有问题的程序要求这些数字在整个JSON中按顺序排列。如你所见,它启动了sub_contents - > 1然后去sub_contents - > 3.我需要编写一个遍历整个事物的函数,并从1开始重新排序。我真的不确定如何做到这一点。我似乎能够得到密钥的名称,但没有设置它。

我的代码:

function reindex_manifest(manifest){
var index = 1;

        $.each(manifest.Components, function(i) {
            $.each(manifest.Components[i].contents, function(n) {
                var obj = manifest.Components[i].contents[n].sub_contents;
                for (var key in obj) {
                    // I CAN READ THE KEY HERE BUT HOW DO I CHANGE IT TO THE
                    //   VALUE OF THE INDEX VARIABLE??
                    console.log(key);
                }
             });
        });
}

1 个答案:

答案 0 :(得分:0)

一种快速方法是:

您需要删除旧密钥,使用新的给定密钥名称复制键值对,然后将其重新注入对象

此外,为了在不引起冲突的情况下实现此目的,您需要切换到each,您无法改变变量。请参阅下面的示例:

function reindex_manifest(manifest){ 
    for (var i in manifest.Components){
        var contentKeys = Object.keys(manifest.Components[i].contents);
        for (var k of contentKeys){

            var content = manifest.Components[i].contents[k];
            var subcontent = manifest.Components[i].contents[k].sub_contents;

            // Check the subcontent key agains the content key
            var subcontent_key = Object.keys(subcontent)[0];
            if (subcontent_key !== k){
               // Re-sequence it, and replace the old one
               subcontent[k] = subcontent[subcontent_key];
               subcontent[subcontent_key] = null;
               delete subcontent[subcontent_key];

               // Update the root
               manifest.Components[i].contents[k].sub_contents = subcontent;
            }
        }
    }

}