在这个对象数组中,可能会出现(!)结构错误,如下所示,我需要纠正它。如您所见,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"
}
]
}
]
}
答案 0 :(得分:1)
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;