0

I have an object and want to add the details of that to the content of JQUERY-CONFIRM.

This is my code:

const obj = {
  'alphabets':['abc', 'xyz', 'pqr'],
  'colors':['red', 'blue', 'purple']
}

$.dialog({
 title: 'Test',
 columnClass: 'col-md-6 col-md-offset-6',
 content: function() {
  for (let key in obj) {
   return `<h3 class='float-left'>${key}</h3>
      <ul class='float-left'>
       <li class='float-left'>${obj[key]}</li>
      </ul>
      `;
  }
 },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.js"></script>

Why am I only getting the first key-value in my content and also why aren't they listing out in the list but showing up as comma-separated values?

nb_nb_nb
  • 1,243
  • 11
  • 36

1 Answers1

1

You loop through the object keys but always return at the first iteration.

You could use .map to map all the obj key/value pairs to the HTML strings and then .join them:

Object.keys(obj).map(mapToHtml).join('')

colors and alphabets were displayed as comma-separated values because you put the entire array into one <li> element: <li class='float-left'>${obj[key]}</li>. To create multiple <li> elements you need to map each element of the array to a new <li>:

const list = obj[key].map(li => `<li class='float-left'>${li}</li>`).join('');

const obj = {
  'alphabets':['abc', 'xyz', 'pqr'],
  'colors':['red', 'blue', 'purple']
}

const mapToHtml = key => {
    const list = obj[key].map(li => `<li class='float-left'>${li}</li>`).join('');
    return `<h3 class='float-left'>${key}</h3><ul class='float-left'>${list}</ul>`;
}

$.dialog({
    title: 'Test',
    columnClass: 'col-md-6 col-md-offset-6',
    content: () => Object.keys(obj).map(mapToHtml).join('')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.js"></script>
Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42