0

I have an array of objects. But sometimes this is just a pure object and in such cases my loop fails. How do I prevent this.

   for(let singleItem of myObj){     // this works fine when I get an array of objects
            myArray.push({
                'Item 1': singleItem .Prop1.text,
                'Item 2': singleItem .Prop2.text
            })
        }

I get an error on for.....of when I have no array but just an Object with key values.

When I get the error, my object `myObj` will be like this.
{
   Prop1: { text: 'testvalue' },
   Prop2: { text: 'testvalue1' }
}

How do I ensure that I can fill my array myArray without any error?

1 Answer 1

2

You can check if myArray is object and then convert it to an array of one object.

for(let singleItem of Array.isArray(myObj) ? myObj : [myObj]){
Sign up to request clarification or add additional context in comments.

1 Comment

this should be answer to so many irrelevant answers here. perfect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.