我正在使用这种特殊格式的javascript数组:
var arr =
["header1", //section header
false, //subsection, no
"1240","1243", //assets
true,"1", //subsection, yes = 1
"1344","1136", //assets
true,"1", //subsection, yes = 1
"1347", //assets
"header2", //section header
false, //subsection, no
"1130"]; //assets
上面的数组有一个序列:
1)带有“标题”的数组是节值。
2)数组中的“false”表示此部分没有任何子部分。所以在JSON中,子值为null。
3)后面跟着false是这些部分的所有资产价值。
4)“true”表示此部分有一个小节。下一个值中的子部分值后跟“true”。在我的示例中,它是1.跟随它是该子部分的所有资产值。
5)遇到带有字符串“header”的下一个数组值时。这是下一部分的开始。
我必须将其转换为以下格式:
{
"templateForm":
[{
"sectionId":"header1",
"values":[
{
"sub":null,
"assets":[1240,1243]
},
{
"sub":1,
"assets":[1344,1136]
},
{
"sub":1,
"assets":[1347]
}
]
},
{
"sectionId":"header2",
"values":[
{
"sub":null,
"assets":[1130]
}
]
}]
}
我尝试了很多但却无法做到。我试图将json格式创建为字符串,但在将其解析为javascript对象时出错。请帮我解决这个问题。
我的不完整代码如下:
function makeJSON(formItems) {
var subString1 = "header";
var strStart = '{"templateForm":[';
var strSection = "";
for (var i = 0; i < formItems.length; i++) {
var isHeader = item.indexOf(subString1) !== -1;
if(isHeader){
strSection += '{"sectionId":'+item[i];
while(item != true || item != false){
}
}
var item = formItems[i] + "";
console.log(item);
if (item == "true") {
var subSectionId = item[++i];
} else if (item == "false") {
var subSectionId = null;
}
}
var strEnd = "]}";
var strFinal = strStart + strSection + strEnd;
console.log(strFinal);
var obj = JSON.parse(strFinal);
console.log(obj);
}
答案 0 :(得分:3)
对于单个插入阶段,您可以使用对象的直接方法。
var array = ["header1", false, "1240", "1243", true, "1", "1344", "1136", true, "1", "1347", "header2", false, "1130"],
result = [],
last = {};
array.forEach(function (a) {
if (a.toString().slice(0, 6) === 'header') {
last.section = { sectionId: a, values: [] };
result.push(last.section);
return;
}
if (typeof a === 'boolean') {
last.sub = { sub: null, assets: [] };
last.section.values.push(last.sub);
last.next = a;
return;
}
if (last.next) {
last.sub.sub = +a;
last.next = false;
return;
}
last.sub.assets.push(+a);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
数据源的格式非常需要。但如果这是您必须使用的,那么下面的代码可以进行转换:
var arr = ["header1",false,"1240","1243",true,"1","1344","1136",true,"1","1347", "header2", false, "1130"];
var result = arr.reduce( (acc, val) => {
if (String(val).indexOf("header") === 0) {
acc.push({
sectionId: val,
values: []
});
return acc;
}
var last = acc[acc.length-1],
lastVal = last.values[last.values.length-1];
if (typeof val === 'boolean') {
last.values.push({
sub: val || null,
assets: []
})
} else if (lastVal.sub === true) {
lastVal.sub = +val;
} else {
lastVal.assets.push(+val);
}
return acc;
}, []);
console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;