Home > Enterprise >  Looping through a json object with the same key
Looping through a json object with the same key

Time:11-14

I have two json objects i am getting remotely and one is of this format

{
    "form": {
        "mounted_language": "en",
        "enctype": "multipart/form-data",
        "hydration_url": "",
        "post_destination": "postFormData()",
        "fields": {
            "title": {
                "type": "text",
                "label": "Title",
                "data-model": "title",
                "value": "",
                "required": true,
                "name": "title",
                "mobile_classes": "col-6",
                "desktop_classes": "col-6"
            },
            "type": {
                "type": "text",
                "label": "Type",
                "data-model": "type",
                "value": "",
                "required": true,
                "name": "type",
                "mobile_classes": "",
                "desktop_classes": ""
            },
            "condition": {
                "type": "text",
                "label": "Condition",
                "data-model": "condition",
                "value": "",
                "required": true,
                "name": "condition",
                "mobile_classes": "col-6",
                "desktop_classes": "col-6"
            },
            "materials": {
                "type": "select",
                "label": "Materials",
                "required": true,
                "data-model": "Materials",
                "mobile_classes": "col-6",
                "desktop_classes": "col-6",
                "name": "materials",
                "selected": "selected",
                "option_has_url": false,
                "options_data_source": "https://example.com/api/url"
            },
            "color": {
                "type": "text",
                "label": "Color",
                "data-model": "color",
                "value": "",
                "required": true,
                "name": "color",
                "mobile_classes": "col-6",
                "desktop_classes": "col-6"
            },
            "weight": {
                "type": "number",
                "label": "Weight",
                "data-model": "weight",
                "value": "",
                "required": true,
                "name": "weight",
                "mobile_classes": "col-6",
                "desktop_classes": "col-6"
            },
            "length": {
                "type": "number",
                "label": "Length",
                "data-model": "lengths",
                "value": "",
                "required": true,
                "name": "lengths",
                "mobile_classes": "col-6",
                "desktop_classes": "col-6"
            },
            "width": {
                "type": "number",
                "label": "Width",
                "data-model": "width",
                "value": "",
                "required": true,
                "name": "width",
                "mobile_classes": "col-6",
                "desktop_classes": "col-6"
            },
            "height": {
                "type": "number",
                "label": "Height",
                "data-model": "height",
                "value": "",
                "required": true,
                "name": "height",
                "mobile_classes": "col-6",
                "desktop_classes": "col-6"
            },
            "pictures": {
                "type": "file",
                "label": "Pictures",
                "x-change": "selectFile($event)",
                "required": true,
                "multiple": true,
                "accept": "image/png, image/jpg, image/jpeg",
                "name": "pictures",
                "value": "",
                "mobile_classes": "col-6",
                "desktop_classes": "col-6"
            },
            "description": {
                "type": "textarea",
                "label": "Description",
                "data-model": "description",
                "value": "",
                "required": true,
                "name": "description",
                "mobile_classes": "col-6",
                "desktop_classes": "col-6"
            }
        }
    }
}

and the other

{
    "data": [{
        "en": "One"
    }, {
        "en": "Two"
    }, {
        "en": "Three"
    }, {
        "en": "Four"
    }]
}

I am getting the first json object and creating a form out of it

$.get("http://localhost:8000/api_routes/agriculture_and_food_structure", function(data) {
    data = JSON.parse(data);

    let original_json_object = data;

    console.log('Original Json Object', original_json_object);

    for (let prop in data) {

        console.log("Key:"   prop);
        for (let prop2 in data.form.fields) {
            console.log("Key2:"   prop2);
            let typ = data.form.fields[prop2].type;
            let label = data.form.fields[prop2].label;

            let text_input = '';


            if (typ == 'text') {
                text_input = '<div ><div ><label for="exampleFormControlInput1" >'   label   '</label> <input type="text" data-model=""  id="exampleFormControlInput1" placeholder=""></div></div>';
            }
            if (typ == 'number') {
                text_input = '<div ><div ><label for="exampleFormControlInput1" >'   label   '</label> <input type="number" data-model=""  id="exampleFormControlInput1" placeholder=""></div></div>';
            }
            if (typ == 'select') {
                let options_data_source = data.form.fields[prop2].options_data_source;
                $.get("http://localhost:8000/data_routes/materials_data", function(dt) {
                    for (let pr in dt) {
                        console.log('Options', dt[pr]);
                    }
                });

                text_input = '<div ><div ><label for="exampleFormControlInput1" >'   label   '</label> <select ></select></div></div>';
            }
            $('#form').append(text_input);
        }
    }

});

console.log('mounted');

I want to get the individual options here

for (let pr in dt) {
console.log('Options', dt[pr]);
}

so that i append to the select box. How can i output the data in the second json object with the identical key?

CodePudding user response:

You have been experiencing a typical problem linked with asynchronuous processing. You have placed the <select> code into the page code before the associated options were returned from the second level AJAX call. In the following snippet I tried to change your code so it will work again. I chose to assign generated ids to all select elements. The options received in the secondary AJAX calls are then inserted into the corresponding select elements that were placed onto the page just moments before:

const dat1={"form": {"mounted_language": "en","enctype": "multipart/form-data","hydration_url": "","post_destination": "postFormData()","fields": {"title": {"type": "text","label": "Title","data-model": "title","value": "","required": true,"name": "title","mobile_classes": "col-6","desktop_classes": "col-6"},"type": {"type": "text","label": "Type","data-model": "type","value": "","required": true,"name": "type","mobile_classes": "","desktop_classes": ""},"condition": {"type": "text","label": "Condition","data-model": "condition","value": "","required": true,"name": "condition","mobile_classes": "col-6","desktop_classes": "col-6"},"materials": {"type": "select","label": "Materials","required": true,"data-model": "Materials","mobile_classes": "col-6","desktop_classes": "col-6","name": "materials","selected": "selected","option_has_url": false,"options_data_source": "https://example.com/api/url"},"color": {"type": "text","label": "Color","data-model": "color","value": "","required": true,"name": "color","mobile_classes": "col-6","desktop_classes": "col-6"},"weight": {"type": "number","label": "Weight","data-model": "weight","value": "","required": true,"name": "weight","mobile_classes": "col-6","desktop_classes": "col-6"},"length": {"type": "number","label": "Length","data-model": "lengths","value": "","required": true,"name": "lengths","mobile_classes": "col-6","desktop_classes": "col-6"},"width": {"type": "number","label": "Width","data-model": "width","value": "","required": true,"name": "width","mobile_classes": "col-6","desktop_classes": "col-6"},"height": {"type": "number","label": "Height","data-model": "height","value": "","required": true,"name": "height","mobile_classes": "col-6","desktop_classes": "col-6"},"pictures": {"type": "file","label": "Pictures","x-change": "selectFile($event)","required": true,"multiple": true,"accept": "image/png, image/jpg, image/jpeg","name": "pictures","value": "","mobile_classes": "col-6","desktop_classes": "col-6"},"description": {"type": "textarea","label": "Description","data-model": "description","value": "","required": true,"name": "description","mobile_classes": "col-6","desktop_classes": "col-6"}}}}, dat2={"data": [{"en": "One"}, {"en": "Two"}, {"en": "Three"}, {"en": "Four"}]},url="https://jsonplaceholder.typicode.com/users/";

$.getJSON(url 1, function(data) {
  let selId=0;
  data = dat1; // this is a "fake" AJAX get(), data comes from dat1  
  let original_json_object = data;
  // console.log('Original Json Object', original_json_object);

  for (let prop in data) {
    // console.log("Key:"   prop);
    for (let prop2 in data.form.fields) {
      // console.log("Key2:"   prop2);
      let typ = data.form.fields[prop2].type;
      let label = data.form.fields[prop2].label;
      let text_input = '';

      if (typ == 'text') {
        text_input = '<div ><div ><label for="exampleFormControlInput1" >'   label   '</label> <input type="text" data-model=""  id="exampleFormControlInput1" placeholder=""></div></div>';
      }
      if (typ == 'number') {
        text_input = '<div ><div ><label for="exampleFormControlInput1" >'   label   '</label> <input type="number" data-model=""  id="exampleFormControlInput1" placeholder=""></div></div>';
      }
      if (typ == 'select') {
        text_input = `<div ><div ><label for="exampleFormControlInput1" >${label}</label><select id="sel${  selId}" ></select></div></div>`;
        let options_data_source = data.form.fields[prop2].options_data_source;
        $.getJSON(url 2, function(dt) { dt=dat2; // fake AJAX call again ... data comes from dat2
          $(`#sel${selId}`).html(dt.data.map(({en})=>`<option>${en}</option>`).join(""));
        });
      }
      $('#form').append(text_input);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form"></form>

CodePudding user response:

To access the data in the second data source (a list of objects) you need to loop over the value at key "data" and extract the option from it. Something like this.

Do this

// for each object in the option's api response.
for (let i = 0; i < dt.data.length;   i) {

    // extract the option
    let option = dt[data][i]["en"]
    
    // print it or do whatever you want
    console.log("Options", option)
}

instead of

for (let pr in dt) {
    console.log('Options', dt[pr]);
}
  • Related