Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
Nested-loop Inside Append

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!