我在数组中有一个这样的数据。
[
{
"teamName": "TeamA",
"players": ["1","2"]
},
{
"teamName": "TeamB",
"players": ["2"]
}
]
我想替换在其他数组中匹配的球员id
players = [
{
"id": "1",
"playername": "alex"
},
{
"id": "2",
"playername": "john"
}
]
所以输出会是这样的
[
{
"teamName": "TeamA",
"players": [
{
"id": "1",
"playername": "alex"
},
{
"id": "2",
"playername": "john"
}]
},
{
"teamName": "TeamB",
"players": [
{
"id": "2",
"playername": "john"
}]
}
]
我试着用for循环来查找,以及它将在哪里查找和替换,但这对我不起作用。
3条答案
按热度按时间3wabscal1#
你可以通过迭代第一个数组并更新该数组中每个元素的players属性来实现这一点。
nimxete22#
一种方法是:
JS Fiddle demo.
参考文献:
Array.prototype.find()
.Array.prototype.map()
.vwkv1x7d3#
构建结果的方法是遍历球队列表,按id查找每个球员,然后将球员记录添加到结果的球员数组中。