0

I have 27 parts to my object, the first 2 are independent while the rest are just the same thing one after another. I am sure it can be optimized with a loop, however I am not sure how to approach this and if anyone can assist, I would be grateful.

Code below:

var BingoData = {Username: username, cardnumber: serial, Cell1: tablecells[0].innerHTML, Cell2: tablecells[1].innerHTML, Cell3: tablecells[2].innerHTML, Cell4: tablecells[3].innerHTML, Cell5: tablecells[4].innerHTML};
1
  • 2
    Names like Cell1, Cell2, Cell3, etc. beg for an array. Commented Dec 28, 2017 at 16:38

2 Answers 2

4

You could make Cells an array and populate it with a for loop.

var BingoData = {Username: username, cardnumber: serial, Cells: []};

for(let i = 0; i < tablecells.length; i++) {
    BingoData.Cells.push(tablecells[i].innerHTML);
}
Sign up to request clarification or add additional context in comments.

7 Comments

Cannot upvote this enough. Never, ever, ever use numbers in a variable name. Instead, just use an array.
Why is i < 28? Should it not be less than 25 since I have 25 cells?
Yep! My typo... I changed it.
And also what does let mean in this case and why to use it?
No, no, no! It should neither be 25 nor 28 but rather tablecells.length !
|
2

1) Identifiers that start with Capital letters are for constructors only

2) you may use an array for the cells

3) you may map the tablecells to their innerHTML property

 const bingo = {
   username,
   cardnumber: serial,
   cells: tablecells.map(cell => cell.innerHTML)
};

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.