Having trouble accessing the properties of the objects in my array in Javascript Code Answer

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.

Answer

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

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

or log lines[0][0].color

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji