0

I need to write a jQuery which would append the JSON Data directly into the a 'div' next to the appropriate 'div' in the HTML. While the actual data is more vast and complicated, I'm putting a simple version for this question.

The html is as below:

<div class="Category">
            <div class="Sub-Category" id="Apple">
                <div id="Parameters"></div>
                <div id="Technicalities"></div>
            </div>
            <div class="Sub-Category" id="Samsung">
                <div id="Parameters"></div>
                <div id="Technicalities"></div>
            </div>
</div>

The JSON data which needs to be added into this is as such:

var StatJSON = {
            "Apple":{
                "Parameters": "Parameter1-2000/Parameter2-5000/Parameter3-3000",
                "Technicalities": "Technicality1-2000/Technicality2-5000/Technicality3-3000",
            },
            "Samsung":{
                "Parameters": "Parameter1-2000/Parameter2-5000/Parameter3-3000",
                "Technicalities": "Technicality1-2000/Technicality2-5000/Technicality3-3000",
            }
        }

The jQuery I have attempted for this, but seems messed up and 'am unable to crack:

$(document).ready(function (){
var StatJsonKeys = Object.keys(StatJSON);

jQuery('.Category .Sub-Category').each(function ($) {
            for (i=0; i<StatJsonKeys.length; i++){
                if (jQuery(this).text() == StatJsonKeys[i]) {
                    if (jQuery(this).children().each(function() {
                        for (j=0; j<StatJsonKeys.length; i++){
                            jQuery(this).attr('id') == StatJsonKeys[i].keys() {
                                jQuery(this).append('<div>' + StatJsonKeys[i].values() + '</div>')
                            }
                        }
                    }   
                }
            }
});

I'm still a novice with this, especially handling JSON, would appreciate any help with this. Thanks!!

         $(document).ready(function (){

         var StatJSON = {
            "Apple":{
                "Parameters": "Parameter1-2000/Parameter2-5000/Parameter3-3000",
                "Technicalities": "Technicality1-2000/Technicality2-5000/Technicality3-3000",
            },
            "Samsung":{
                "Parameters": "Parameter1-2000/Parameter2-5000/Parameter3-3000",
                "Technicalities": "Technicality1-2000/Technicality2-5000/Technicality3-3000",
            }
        }

        var StatJsonKeys = Object.keys(StatJSON);

        jQuery('.Category .Sub-Category').each(function ($) {
            for (i=0; i<StatJsonKeys.length; i++){
                if (jQuery(this).text() == StatJsonKeys[i]) {
                    if (jQuery(this).children().each(function() {
                        for (j=0; j<StatJsonKeys.length; i++){
                            jQuery(this).attr('id') == StatJsonKeys[i].keys() {
                                jQuery(this).append('<div>' + StatJsonKeys[i].values() + '</div>')
                            }
                        }
                    }   
                }
            }
        
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<body>
        <div class="Category">
            <div class="Sub-Category" id="Apple">
                <div id="Parameters"></div>
                <div id="Technicalities"></div>
            </div>
            <div class="Sub-Category" id="Samsung">
                <div id="Parameters"></div>
                <div id="Technicalities"></div>
            </div>
        </div>
 </body>
Mithun Uchil
  • 347
  • 1
  • 12
  • [JSON is a textual, language-independent data-exchange format](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – mplungjan Dec 16 '19 at 13:11

2 Answers2

1

Your JavaScript is very invalid, for example

jQuery(this).attr('id') == StatJsonKeys[i].keys() { looks like you want to change the ID to something else and then run some kind of function...

Here is what I think you meant to do.

  1. Loop over the object, not the HTML - I renamed the object since it is not JSON - see the 3rd example if you want to loop the HTML, not the object
  2. use the jQuery selector that matches the object keys
  3. You must have unique IDs so I changed the divs' IDs to class

const stats = {
  "Apple": {
    "Parameters": "Parameter1-2000/Parameter2-5000/Parameter3-3000",
    "Technicalities": "Technicality1-2000/Technicality2-5000/Technicality3-3000",
  },
  "Samsung": {
    "Parameters": "Parameter1-2000/Parameter2-5000/Parameter3-3000",
    "Technicalities": "Technicality1-2000/Technicality2-5000/Technicality3-3000",
  }
}

$(function() {
  $.each(stats, (key, val) => {
    $("#"+key +" .Parameters").html(val["Parameters"]); // we COULD loop over the sub cat here 
    $("#"+key +" .Technicalities").html(val["Technicalities"]);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<body>
  <div class="Category">
    <div class="Sub-Category" id="Apple">
      <div class="Parameters"></div>
      <div class="Technicalities"></div>
    </div>
    <div class="Sub-Category" id="Samsung">
      <div class="Parameters"></div>
      <div class="Technicalities"></div>
    </div>
  </div>
</body>

It is also possible to not even have HTML but generate the necessary HTML from the object

const stats = {
  "Apple": {
    "Parameters": "Apple Parameter1-2000/Parameter2-5000/Parameter3-3000",
    "Technicalities": "Apple Technicality1-2000/Technicality2-5000/Technicality3-3000",
  },
  "Samsung": {
    "Parameters": "Samsung Parameter1-2000/Parameter2-5000/Parameter3-3000",
    "Technicalities": "Samsung Technicality1-2000/Technicality2-5000/Technicality3-3000",
  }
}

$(function() {
  const $cat = $("#category");
  $.each(stats, (key, val) => {
    let $subCat = $("<div/>",{"class":"subCategory","id":key})
    $.each(val, (key,val) => {
      $("<div/>",{"class":key}).html(val).appendTo($subCat);
    })
    $cat.append($subCat)
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<div id="category"></div>

Last example, in case your HTML is smaller than your object and you want to access the key using the HTML instead of what I did in my first example

const stats = {
  "Apple": {
    "Parameters": "Parameter1-2000/Parameter2-5000/Parameter3-3000",
    "Technicalities": "Technicality1-2000/Technicality2-5000/Technicality3-3000",
  },
  "Samsung": {
    "Parameters": "Parameter1-2000/Parameter2-5000/Parameter3-3000",
    "Technicalities": "Technicality1-2000/Technicality2-5000/Technicality3-3000",
  }
}

$(function() {
  $(".Sub-Category").each(function() {
    let item = stats[this.id]; // using the DIV ID to access the relevant object item
    $("div",this).each(function() { // the divs under "this" sub-category
      $(this).html(item[this.className]); // each div is now "this"
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<body>
  <div class="Category">
    <div class="Sub-Category" id="Apple">
      <div class="Parameters"></div>
      <div class="Technicalities"></div>
    </div>
    <div class="Sub-Category" id="Samsung">
      <div class="Parameters"></div>
      <div class="Technicalities"></div>
    </div>
  </div>
</body>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 2
    Thanks @mplungjan for the elegant answer and very detailed reply!! :) – Mithun Uchil Dec 16 '19 at 13:34
  • 1
    @MithunUchil See the last example. It is the closest to your initial question since it uses the HTML you made to access the object instead of the other way around – mplungjan Dec 17 '19 at 07:52
1

Please find below code that I feel should satisfy your requirement -

var StatJSON = {
    "Apple": {
        "Parameters": "Parameter1-2000/Parameter2-5000/Parameter3-3000",
        "Technicalities": "Technicality1-2000/Technicality2-5000/Technicality3-3000"
    },
    "Samsung": {
        "Parameters": "Parameter1-4000/Parameter2-10000/Parameter3-6000",
        "Technicalities": "Technicality1-2000/Technicality2-5000/Technicality3-3000"
    }
};

const $category = $("<div/>", {
    class: "Category" // used class because there can be multiple categories.
});

$.each(StatJSON, function(subCatName, subCatContent) {
    let $subCategory = $("<div/>", {
        class: "Sub-Category",
        id: subCatName
    });
  
    $.each(subCatContent, function(subCatStatName, subCatStatContent) {
        let $subCategoryStat = $("<div/>", {
         class: subCatStatName
        });
    
        $subCategoryStat
            .html(subCatStatContent)
            .appendTo($subCategory);
    });
  
    $subCategory.appendTo($category);
});

$("#result").html($category);
<div id="result"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  • 1
    I made you a snippet. I do not find the code very elegant compared to either of mine... Why all the HTML strings when you use jQuery anyway? – mplungjan Dec 16 '19 at 13:22
  • 1
    Thanks @harshadk258 for the quick and neat reply!! Both the approaches are effective and very useful! :) – Mithun Uchil Dec 16 '19 at 13:35
  • Hi!! @harshadk258. Could you help me with how I can extract the JSON sub-headings 'Parameters' & 'Technicalities' like how you have used 'StatJSON[v].Parameters' & 'StatJSON[v].Technicalities' for the values. I tried 'StatJSON[k].Parameters' & 'StatJSON[k].Technicalities' but this didn't work. Thanks again!! :) – Mithun Uchil Dec 17 '19 at 03:12
  • @mplungjan Thank you for your edit. I didn't try to make the code elegant or to abide by the concepts of jQuery. Your answer and comment really helped me out there. Appreciate your feedback. – harshadk258 Dec 17 '19 at 07:36
  • Hey @MithunUchil Could you elaborate on what didn't work exactly while extracting the subheadings as you mentioned? – harshadk258 Dec 17 '19 at 09:03
  • Hey @harshadk258, my query was pertaining to the previous solution given by you. As it was simple and easy to understand for a novice like me, would you be kind enough to paste it below as an additional answer? I would upvote the same! :) – Mithun Uchil Dec 17 '19 at 13:11