1

How to loop through an object in react?

I know this is a silly question, but I cant for the life of me find the answer online.

I want to loop through an object that is a list.

const [tagList, setTagList] = useState([])

Before looping, I also do this with the list:

setTagList(makeListOfTags(tagString))

function makeListOfTags(tagLine) {
        tagLine = JSON.stringify(tagLine)
        tagLine = tagLine.replace('{', '')
        tagLine = tagLine.replace('}', '')
        tagLine = tagLine.replace('"tagString":', '')
        tagLine = tagLine.replace('"', '')
        tagLine = tagLine.replace('"', '')
        const tags = tagLine.split(" ")

        return tags;
    }

tagString is formated like this: {tagString: "tag a", "tag b"} the tags variable, is a list containing the tags in tagsString: ["tag a", "tag b"] I use setTagList to make tagList like const tags.

But Im struggling to loop the tagList. I've tried:

for (let i = 0; i > tagList.length; i++)

But that gives: Uncaught TypeError: Cannot read properties of undefined (reading 'lenght')

I've tried:

for (let i = 0; i > Object.keys(tagList).length; i++)

But that gives: Uncaught TypeError: Cannot read properties of undefined (reading 'lenght')

I've tried:

for (let i = 0; i > tagList.tagList.length; i++) {

But that gives: Uncaught TypeError: Cannot read properties of undefined (reading 'lenght')

if I do this right before the loop:

console.log(typeOf tagList)

It says that tagList is an object.

So how do I do the loop?

  • Does this answer your question? [Loop through an array in JavaScript](https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript) – lucasvw Jun 22 '22 at 17:52

1 Answers1

0

You may have length spelled incorrectly in your code.

If your typeError states reading 'lenght', check if there is a line number next to your typeError, and navigate to that line in your code. There may a typo there.

Otherwise, your for loop examples use a greater than sign, rather than a less than sign. It should look like this:

for (let i = 0; i < Object.keys(tagList).length; i++)

If it isn't looping correctly after your typeError is fixed, your issue may be there. If your tagList is truly an object, Object.keys should work for looping.

gojanedoe
  • 1
  • 1