Home > Software engineering >  Create an array from 'for of' loop outputs
Create an array from 'for of' loop outputs

Time:09-28

I have a for of statement in JS that returns HTML element ids but they are in multiple outputs. I would like to take these outputs and put them in an array.

For example the HTML is:

<div>
    <button id="savebtn-1"></button>
</div>
<div>
    <button id="savebtn-2"></button>
</div>

and my JS is:

const elements = document.querySelectorAll("button");
for (const element of elements) {
    let id = elements.getAttribute("id");
}

console.log(id) will show:

savebtn-1

savebtn-2

How can I get these outputs into an array?

Thanks for any attention you may give this question.

CodePudding user response:

Make another array and store all the id's inside that array.

const resultArray = [];
const elements = document.querySelectorAll("button");

for (const element of elements) {
    const id = element.getAttribute("id");
    resultArray.push(id);
}
console.log(resultArray);
<div>
<button id = "savebtn-1">Button 1</button>
</div>
<div>
<button id = "savebtn-2">Button 2</button>
</div>

CodePudding user response:

Use Array.from() on the NodeList and a custom mapper to extract the IDs

const idArray = Array.from(
  document.querySelectorAll("button"),
  ({ id }) => id
);

console.log(idArray);
<div>
  <button id="savebtn-1">Button #1</button>
</div>
<div>
  <button id="savebtn-2">Button #2</button>
</div>

CodePudding user response:

You can create an empty array and push ids into that array.

const elements = document.querySelectorAll("button");

const idArray = [];

for (const element of elements) {
    let id = elements.getAttribute("id");
    idArray.push(id);
}

console.log('idArray ', idArray);
  • Related