我有一个看起来像这样的数组(其中包含更多项,但结构相同):
[
{
"users": [
"speciality": "surgery",
{
"name": "John",
"location": "USA",
"age": "34",
},
{
"name": "John",
"location": "California",
"address": "Silk Road 123"
},
{
"name": "Jane",
"last-name": "Edmus"
"location": "USA"
}
]
},
]
我正在尝试以这种方式映射该数组,如果name属性在两个对象中相等,则应将其映射为仅一个p标签,并且在“查看更多”标签之后出现许多位置。是我目前拥有的东西,它不起作用:
mapArray = () => {
const test= this.state.test;
return test.map(i =>
i.users.map((user,index) =>
<div>
<p>{i.speciality}</p>
user.name[index] === user.name[index + 1]
? <p>{user}</p> <p>See more></p> <p>{user.location}}
: <p>{user}<p>{user.location}</p>
</div>
}
答案 0 :(得分:0)
您可以使用本机js函数,但一个简单的选择是使用lodash groupby。以下大致介绍了如何使用lodash(未经验证的代码)完成此操作:
// we first need to group the names for each object in the test array
getGroups = test => {
return test.map(item => {
item.groupedUsers = _.groupBy(item.users, user => user.name)
return item
})
}
// then we check and iterate through grouped data
render() {
const groupedData = getGroups(this.state.test)
return (
<div>
{ groupedData.map(item => {
return Object.keys(item.groupedUsers).map(user =>
<div>
{ item.groupedUsers[user].length > 1 ? <p>{user}</p> <p>See more></p> : <p>{user}</p> }
</div> )
} )
}
</div>
)
}