Loop through an array of objects

My console.log within my for loop is printing undefined

for (let i = 0; i < importedArray.length; i++) {
    console.log(importedArray[i].title);
}

Whereas this;

for (let i = 0; i < importedArray.length; i++) {
    console.log(importedArray[i]);
}

Prints;

{
 title: 'title one',
content: 'joiheihoe'
}
{
 title: 'title two',
content: 'joiheihoe'
}

The importedArray is the result of a query from my mongoDB collection.

Add the following console.log statement before the above line and see what you get.

console.log(importedArray);

If importedArray looks like the following, there is no reason your code above should not display what you expect.

[
  {
    title: 'title one',
    content: 'joiheihoe'
  },
  {
    title: 'title two',
    content: 'joiheihoe'
  }
]

https://repl.it/@rmdawson71/testing-for-loop-on-array

Unfortunately it looks exactly like that!

Then I would need to see your full code. Can you put it in repl.it?

your code seems fine. provide more info please

I’ve tried to re-create it here
https://repl.it/join/xeclejrk-chrisbull1

okay, let me check it out

This code works from my end. Check this out:

Yeah i can get that bit to work when I was testing. However the array from my query is the one that is commented out, ‘importedArrayTwo’ this is the one I can’t get to work

I see where your issue is, you should enclose the value of _id in quotation marks because it is a string and not a number.

Like in the image below:

I hope this solves your issue

I’m not sure I can do that; the contents of the array are directly from a mongoose query;

importedArrayTwo = DatabaseImport.find().limit(3);

How’s your back end code when sending the data to the front end? Are you using the JSON.stringify( mongooseObj ) function to properly return a valid JSON object to the front end?

The stringify object if used before sending the data to the front end should put the quotation marks for you to make it a valid JSON object. Then you should have no problems on the front end.

This is all in the backend though? All in node, there is no front end, would I still need to use it.

I am getting the result of the query and then checking if a value is equal to another value.

As an aside; using .lean() at the end of the query has got this to work however I now can’t use .save(0 if I want to update the record in the future

try using the same JSON.stringify function. See how it behaves. I have personally never had that issue in the backend. I know lean also helps but it’s not a good option unless you are done modifying the data. Like you said, there might be a problem with the save() function