我尝试将fk_city与'list_cities'中对象的$id进行匹配,然后计算它们出现的次数。
const list_cities = [
{ $id: '15FG', name: 'Pittsburg' },
{ $id: '50HS', name: 'Los Angeles' },
];
const list_places = [
{
$id: '59HE',
fk_city: '15FG',
name: 'Some Place',
description: 'I have text here',
slug: 'some-place',
},
{
$id: '94KR',
fk_city: '15FG',
name: 'Another Place',
description: 'This is the description',
slug: 'another-place',
},
{
$id: '05HE',
fk_city: '50HS',
name: 'The last Place',
description: 'More text here',
slug: 'the-last-place',
},
];
我基本上是在尝试计算每个城市的位置数量,但到目前为止,我无法让它输出一个新的数组,该数组只显示:
[
{city: "Pittsburg", places: "2"}
{city: "Los Angeles", places: "1"}
]
我试过将list_cities中的$id与list_places中的属性fk_city进行匹配,但我不知道如何计算相同的$id在places数组中出现的次数。这应该是一个外键关系,但我使用的后端只能提供来自端点的原始id,因此我需要手动Map$id。
任何帮助都很感激!谢谢!
3条答案
按热度按时间pcww981p1#
尝试循环
list_cities
并计算list_places
中出现的次数:envsm3lx2#
如果
list_places
很长,你可以通过先创建一个查找表fk_city
,然后再创建一个查找表map
来避免多次迭代。gxwragnw3#
这个代码对我有效,请检查它可以帮助你