I am working on a simple React project. I have this Map object books
with book.id as the keys and book object as the values. So i can create a Map object but I cannot iterate the Map use for... of
or forEach
.
This is part of the code
const books = this.props.readingBooks;
let KEYS = [];
let VALUES = [];
for (const book of books) {
let [key, value] = book;
KEYS.push(key);
VALUES.push(value);
}
When i use the code up, i always have this error:
I'll write this in an answer because I need to show you some code even though we haven't yet quite figured out what's wrong with your code.
First off, the error you show means that some code is trying to iterate something that isn't an iterable. If your assertion is correct that the error comes from the for/of
loop, then it's telling you that books
is not an iterable, therefore, not a Map object.
You can see with this simple example, that if books
is a legit Map
object, then your code works fine. You can run it right here in this snippet and see that it works if books
is a proper Map
object.
const books = new Map([["key1", "val1"], ["key2", "val2"]]); let KEYS = []; let VALUES = []; for (const book of books) { let [key, value] = book; KEYS.push(key); VALUES.push(value); } console.log(KEYS); console.log(VALUES);
So, either books
isn't a proper Map
object like you think it is or there is something else going on in your real code that you're not showing us here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.