[英]Error while iterating over array elements
I have below array -我有以下数组 -
var arr= [
{
id:1,
name:"some name 1",
email:"somename1@email.com"
},
{
id:2,
name:"some name 2",
email:"somename2@email.com"
}
]
I want to iterate in a way that, I want output as string (semi colun separated name string)-我想以一种方式迭代,我希望 output 作为字符串(半列分隔的名称字符串)-
"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>
)
An easy way to implement what you're looking for is by using Array.prototype.reduce()实现所需内容的一种简单方法是使用Array.prototype.reduce()
You can try out the following code by using ES6:您可以使用 ES6 尝试以下代码:
const arr= [ { id:1, name:"some name 1", email:"somename1@email.com" }, { id:2, name:"some name 2", email:"somename2@email.com" } ] const newString = arr.reduce((preVal, newVal) => `${preVal} ${preVal? ";": ""} ${newVal.name} `, "") console.log(newString)
The error usually means you're trying to render something that's not directly a React component该错误通常意味着您正在尝试渲染不直接是 React 组件的东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.