1

I need to make two loops from one data point to create multiple divs.

Data Example:

let data = [
  [
    {
        title: '1'
    },
    {
        title: '2'
    }
  ],
  [
    {
        title: '3'
    },
    {
        title: '4'
    }
  ]
];

If I loop in here, I get 2 arrays with 2 sets of obj each.

I need to append a parent div for each array and inside the appended div, loop again to append the information from the obj.

To look something like this:

<div class="first-array"> //Class is just for reference
  <span>
    <p>title</p>
  </span>
  <span>
    <p>title</p>
  </span>
</div>
<div class="second-array"> //Class is just for reference
  <span>
    <p>title</p>
  </span>
  <span>
    <p>title</p>
  </span>
</div>

How can I be able to achieve this?

2
  • 2
    <p>title</p> or <p>1</p>, <p>2</p>, etc? Also, <p> should not be within <span> Commented Sep 7, 2021 at 23:46
  • Use nested loops. The outer loop processes the outer array and creates the div elements. The inner loop processes the inner arrays and creats the span and title elements. Commented Sep 7, 2021 at 23:47

2 Answers 2

2

You can use Array.map to wrap each nested item's title property in the appropriate tags, then use Array.join to convert the array to a string:

let data=[[{title:"1"},{title:"2"}],[{title:"3"},{title:"4"}]];

const HTML = data.map(e => '<div>'+e.map(f => `<span><p>${f.title}</p></span>`).join('')+'</div>').join('')

console.log(HTML);

document.write(HTML);

Sign up to request clarification or add additional context in comments.

Comments

2

jQuery's .append() can take an array of objects so you can map your original data to the structure you want

let data = [[{"title":"1"},{"title":"2"}],[{"title":"3"},{"title":"4"}]]

$(document.body).append(data.map(titles =>
  $("<div>").append(titles.map(({ title: text }) =>
    $("<span>").append($("<p>", { text }))))))
div, span, p {
  display: block;
  border: 1px solid;
  padding: .5rem;
  margin: .5rem;
  position: relative;
}
div:after, span:after, p:after {
  position: absolute;
  font-size: 0.6em;
  color: gray;
  top: 0;
  left: 0;
}
div:after { content: "div"; }
span:after { content: "span"; }
p:after { content: "p"; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.