将对象转换为数组并删除对象实例

时间:2016-01-09 18:32:38

标签: javascript arrays

在这个对象数组中,可能会出现(!)结构错误,如下所示,我需要纠正它。如您所见,data应该是带有对象的数组。有时候它是一个有一个物体的物体。在此示例中,group的最后一个元素包含字段"1",这是错误的。此字段名称可以具有不同的名称。我需要删除它。

{
    "group" : [
        {
            "title" : "title 1",
            "data" : [
                {
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                },
                {
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                },
                {
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                }
            ]
        },
        {
            "data" : {  // <-- should be array
                "1" : { // <-- wrong
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                }
            }
        }
    ]
}

结果应为:

{
    "group" : [
        {
            "title" : "title 1",
            "data" : [
                {
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                },
                {
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                },
                {
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                }
            ]
        },
        {
            "data" : [
                {
                    "field 1" : "Lorem ipsum",
                    "field 2" : "dolor"
                }
            ]
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
var data = {
    "group" : [{
            "title" : "title 1",
            "data" : [
                { "field 1" : "Lorem ipsum" }
            ]
        }, {
            "data" : {
                "1" : { "field 1" : "Lorem ipsum" }
            }
        }
    ]
};

// check each group
data.group.forEach(function (g) {
    // is it an array (simple check for "length" property)
    if (typeof g.data.length === "undefined") {
        // if not, convert "data" to an array and replace it in-place
        g.data = Object.keys(g.data).map(function (d) {
                return g.data[d];
            })
    }
});

console.log(JSON.stringify(data));
&#13;
&#13;
&#13;