1

I currently have this function that populates an array with objects with 2 properties, color and angle.

function populateArray() {
  let lines = [];
  let numOfLines = 200;
  let colorArray = [
    '#0f41ff',
    '#f5680e',
    '#9536ac',
    '#d8ad00',
    '#bd58a4',
    '#f8c586',
    '#406309',
    '#ed0f00',
  ];

  for (let i = 0; i < numOfLines; i++) {
    let randomColorNumber = getRandomInt(colorArray.length);
    let randomColor = colorArray[randomColorNumber];
    let randomAngle = getRandomFloat(10, 20);
    if (i % 2 === 1) {
      randomAngle = randomAngle * -1;
    }
    lines.push([{ color: randomColor, angle: randomAngle }]);
  }
  return lines;

That is working just fine, and when I console.log(lines) I get the array of objects perfectly.

I can even do console.log(lines[0]), and that works fine. It returns something like this: {color: "#f5680e", angle: -13.180879351807855}.

But, when I try to access the properties of an index, it returns undefined. For example, console.log(lines[0].color) returns undefined.

This is my problem, I need to access these values, but I can't. It's weird though, as I can access the whole object itself, and there is only one function that populates my array, and no asynchronous calls are being made.

Thank you for the help.

1
  • 2
    lines.push([{ color: randomColor, angle: randomAngle }]) This always pushes an array with a single element in it to lines. Remove the [ and ] there. (Or log lines[0][0].color.) Commented Feb 8, 2021 at 15:09

1 Answer 1

1

Push object: lines.push({...}); not array lines.push([...]);

lines.push({ color: randomColor, angle: randomAngle });

or log lines[0][0].color

Sign up to request clarification or add additional context in comments.

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.