Rue Vitale
Rue Vitale

Reputation: 1891

how to iterate over objects of objects and display in mustache template

I have the following data structure

{ 'the-subtle-art-of-not-givng-a-f': { "id: "test", "title": "test"}, "the-hamset": {"id": "test", "title": "test"}}

how can I display the title in a mustache template?

Upvotes: 1

Views: 309

Answers (1)

Michael Rodriguez
Michael Rodriguez

Reputation: 2176

jQuery

HTML:

<div id="output">

</div>

<script type="text/template" id="titles">
    <ul>
        {{#titles}}
            <li>{{title}}</li>
        {{/titles}}
    </ul>
</script>

JS:

$(document).ready(function(){
    const template = $('#titles').html();
    const output = $('#output');

    const object = {
        'the-subtle-art-of-not-givng-a-f': {
            "id": "test", "title": "test1"
        },
        "the-hamset": {
            "id": "test", "title": "test2"
        }
    };

    let titles = [];
    for (const property in object) {
        if (object.hasOwnProperty(property)) {
            if (object[property].title) {
                titles.push( { title: object[property].title });
            }
        }
    }

    const data = { titles };

    const result = Mustache.render(template, data);
    output.append(result);
});

Example


Vanilla JS:

HTML:

<div id="output">

</div>

<script type="text/template" id="titles">
    <ul>
        {{#titles}}
            <li>{{title}}</li>
        {{/titles}}
    </ul>
</script>

JS:

const callback = function() {
  const template = document.querySelector('#titles').innerHTML;
  const output = document.querySelector('#output');

  const object = {
    'the-subtle-art-of-not-givng-a-f': {
     "id": "test", "title": "test1"
    },
    "the-hamset": {
     "id": "test", "title": "test2"
    }
  };

  let titles = [];
  for (const property in object) {
    if (object.hasOwnProperty(property)) {
      if (object[property].title) {
        titles.push( { title: object[property].title });
      }
    }
  }

  const data = { titles };
  const result = Mustache.render(template, data);
  output.innerHTML = output.innerHTML + result;
};

if (
  document.readyState === "complete" ||
  (document.readyState !== "loading" && !document.documentElement.doScroll)
) {
  callback();
} else {
  document.addEventListener("DOMContentLoaded", callback);
}

Example

Upvotes: 0

Related Questions