Home > other >  Creating Html to Json using .map, Facing issues to format it in exact format
Creating Html to Json using .map, Facing issues to format it in exact format

Time:06-07

I am creating dynamic sections with section ids and fields data and I am getting all the data with section ids. Creating JSON using .map() function with section ids and data values, facing some issues like the JSON format is not right which i want.

Please also advise it is the right way to do the dynamic sections? I am going right?

Here is my HTML code:

<section id="section-1" >
<input id="input1" value="input1">
<input id="input2" value="input2">
</section>
<section id="section-2" >
<input id="input3" value="input3">
<input id="input4" value="input4">
</section>

and Jquery code

var section = $(".section").map(function()
        {
            var section_obj = {};
            var section_id = $(this).attr("id");
            
            var data = $(this).find(':input').map(function()
            {
                var obj = {};
                obj['id'] = $(this).attr("id");
                obj['value'] = $(this).val();
                return obj;
            }).get();

            section_obj[section_id] = data;

            return section_obj;

        }).get();

RESULTS

[{"section-1":[{"id":"input1","value":"input1"},{"id":"input2","value":"input2"}]},{"section-2":[{"id":"input3","value":"input3"},{"id":"input","value":"input4"}]}]

I want the result should be the below just need t remove the first section } with 2nd section start { like simple just remove the },{

[{"section-1":[{"id":"input1","value":"input1"},{"id":"input2","value":"input2"}],"section-2":[{"id":"input3","value":"input3"},{"id":"input","value":"input4"}]}]

CodePudding user response:

Try this:

var mergedSections = {};
var section = $(".section").map(function() {
  var section_id = $(this).attr("id");

  var data = $(this).find(':input').map(function() {
    var obj = {};
    obj['id'] = $(this).attr("id");
    obj['value'] = $(this).val();
    return obj;
  }).get();

  mergedSections[section_id] = data;
});
console.log(mergedSections);

however you may wrap it with [] to reach your result:

console.log([mergedSections]);

working demo: https://jsfiddle.net/310wLyz9/

  • Related