1

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);
    }
8
  • 3
    What code have you tried? Where are you stuck? What errors are you getting? Commented Aug 24, 2017 at 12:43
  • 2
    Where does the data come ? Its format is pretty bad IMO. Commented Aug 24, 2017 at 12:46
  • @NathanP.Can you suggest me a good format Commented Aug 24, 2017 at 12:48
  • @Cruiser: I had added the code Commented Aug 24, 2017 at 12:48
  • The one you are trying to convert it to seems better to me. The data should come already formatted, but since I don't know how you get it, I cannot tell. Commented Aug 24, 2017 at 12:50

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.