Search code examples
javascriptarraysjsonreactjsnested-forms

How to make dynamic checkbox input from JSON formed database


can anyone help me how to make dynamic checkbox?

so, i have JSON data like this

 [ {
  "categoryName" : "Category 1",
  "items" : [ {
    "value" : "value1",
    "label" : "label1"
  }, {
    "value" : "value2",
    "label" : "label2"
  } ]
}, {
  "categoryName" : "Category 2",
  "items" : [ {
    "value" : "value3",
    "label" : "label3"
  } ]
} ]

as i know that checkbox inputs are require property like value and label, so all i need to do is fill that property with data from that JSON, the problem is how to make this checkbox is auto-generate based on data from that JSON.

the result should be like THIS PICTURE

PS: sorry for my bad english


Solution

  •   const array = [ {
      "categoryName" : "Category 1",
      "items" : [ {
        "value" : "value1",
        "label" : "label1"
      }, {
        "value" : "value2",
        "label" : "label2"
      } ]
    }, {
      "categoryName" : "Category 2",
      "items" : [ {
        "value" : "value3",
        "label" : "label3"
      } ]
    } ]
    
    let category = "";
    let checkboxes = "";
    
    array.forEach(el => {
    category += `<h3>${el.categoryName}</h3>
    `;
     if (el.items.length > 0) {
     el.items.forEach(v => {
     checkboxes += `<input type ="checkbox" value="${v.value}"> <label for 
     ="${v.value}">${v.label}</label>`;
      });
     } else {
    checkboxes = ``;
    }
    });
    

    Not tested but i hope it gives you a clue to solve your problem.