gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:58:28 24 4
gpt4 key购买 nike

在此对象数组中,可能(!)存在如下所示的结构错误,我需要纠正这些错误。如您所见,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"
}
]
}
]
}

最佳答案

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));

关于javascript - 将对象转换为数组并删除对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34697359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com