Home > Software engineering >  Error while iterating over array elements
Error while iterating over array elements

Time:02-18

I have below array -

var arr= [ 
{
 id:1,
 name:"some name 1",
 email:"[email protected]"
},
{
 id:2,
 name:"some name 2",
 email:"[email protected]"
}
]

I want to iterate in a way that , I want output as string (semi colun separated name string)-

"some name 1;some name 2"

I iterated it in below manner -

var name="";
arr.forEach( (item:any)=> {
name =item.name ";";
});

But I am getting below error -

UncoughtError : Objects are not valid as react child (found object with keys {id , name , email}). If you want to render collection of child use array instead.

EDIT :

return (
<span> {name} </span>
)

CodePudding user response:

An easy way to implement what you're looking for is by using Array.prototype.reduce()

You can try out the following code by using ES6:

const arr= [ 
    {
     id:1,
     name:"some name 1",
     email:"[email protected]"
    },
    {
     id:2,
     name:"some name 2",
     email:"[email protected]"
    }
    ]

const newString = arr.reduce((preVal, newVal) => `${preVal} ${preVal ? ";" : ""} ${newVal.name} `, "")

console.log(newString)

CodePudding user response:

The error usually means you're trying to render something that's not directly a React component

  • Related