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

116
Views
Pass an array of objects to another function onclick

I just want to ask how to pass an array of objects to another function. I have a function

 function btnB(weekly) {
    console.log(weekly);
 }

 function btnA() { 
    const array = [{ abc : 123 }, { def : 456 }]        
    div.innerHTML = `<div onclick="btnB(${array[0]});"`;
    divList.appendChild(div);        
 }

 btnA();

And I'm getting an error

Uncaught SyntaxError: Unexpected identifier
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can't substitute an object like that in a template literal. It converts the object to a string, which returns [Object object].

Use JSON.stringify() to convert it to an object literal.

function btnA() { 
    const array = [{ abc : 123 }, { def : 456 }]        
    div.innerHTML = `<div onclick='btnB(${JSON.stringify(array[0])});'`;
    divList.appendChild(div);        
 }

You also should use single quotes around the onclick value, because JSON uses double quotes around the object keys.

about 4 years ago · Juan Pablo Isaza Report

0

function btnB(weekly) {
   console.log(weekly);
}

function btnA() { 
   const array = [{ abc : 123 }, { def : 456 }];
   const div = document.createElement('div'); // delete if useless
   div.addEventListener('click', () => {
     btnB(array[0])
   });
   divList.appendChild(div);        
}
about 4 years ago · Juan Pablo Isaza Report

0

I'm assuming the [0] is part of your attempt to solve this, but based on the question asking to pass an array of objects to the click handler, I'll refer to that instead.

Inline event handlers are deprecated and problematic anyway, but using them in HTML generated by JavaScript completes the circle in an absurd way. It would be a lot easier and more robust (and secure) to attach the click handler via JavaScript as well, as follows:

const array = [{ abc: 123 }, { def: 456 }]        
div.innerHTML = '<div></div>' // Just the inner div without onclick
div.firstElementChild.addEventListener('click', () => btnB(array))
divList.appendChild(div)
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!