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.

Unfortunately it looks exactly like that!

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

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.