[英]Converting Array of String in a particular JSON Format using Jquery or Javascript
我有這種特定格式的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)具有“ header”的數組是段值。
2)數組中的“ false”表示此部分沒有任何子部分。 因此,在JSON中,子值為null。
3)后面跟着是該節的所有資產值。
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);
}
對於插入的單個階段,可以對對象使用簡單的方法。
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; }
數據源的格式有很多不足之處。 但是,如果這是您必須使用的方法,那么可以使用以下代碼進行轉換:
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);
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.