简体   繁体   中英

Converting Array of String in a particular JSON Format using Jquery or Javascript

I am having a javascript array in this particular format:

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

The above array is having a sequence:

1) The array with "header" is the section value.

2) "false" in the array indicates that this section is not having any subsection. So in JSON the sub value is null.

3) Followed by false are all the assets value for the sections.

4) "true" indicates that this section is having a subsection. The subsection value in the next value followed by "true". In my example it is 1. Following it are all assets values for that subsection.

5) When the next array value with string "header" is encountered. It is start of the next section.

I have to convert it into the format:

{
  "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]
        }
        ]
    }]
}

I had tried a lot but not able to do it. I tried to create the json format as string but got error at the time of parsing it as javascript object. Please help me to solve this problem.

My incomplete code are as follows:

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

You could use a straight forward approach with an object for the single stages of inserting.

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

The format of the data source leaves much to desire for. But if this is what you must work with, then following code can make the conversion:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM