Pass an array of objects to another function onclick

Viewed 172

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
3 Answers

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.

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

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