reactjs 如何计算一个数组中的属性在另一个数组中出现的次数,并将匹配项Map到新数组?

omvjsjqw  于 2023-01-25  发布在  React
关注(0)|答案(3)|浏览(125)

我尝试将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。
任何帮助都很感激!谢谢!

pcww981p

pcww981p1#

尝试循环list_cities并计算list_places中出现的次数:

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"}
    ] 
    
const cityCount = [];
for (const c of list_cities) {
    cityCount.push({
    city: c.name,
    places: list_places.filter(p => p.fk_city === c.$id).length
  })
}
console.log(cityCount);
envsm3lx

envsm3lx2#

如果list_places很长,你可以通过先创建一个查找表fk_city,然后再创建一个查找表map来避免多次迭代。

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', },];

const placeCount = {};
for (const { fk_city } of list_places) {
  placeCount[fk_city] = (placeCount[fk_city] ?? 0) + 1;
}

const result = list_cities.map((city) => ({
  ...city,
  placeCount: placeCount[city.$id],
}));

console.log(result);
gxwragnw

gxwragnw3#

这个代码对我有效,请检查它可以帮助你

list_cities.forEach((resp) => {
  list_places.forEach((res) => resp.$id === res.fk_city && (resp.places ? (resp.places = resp.places + 1): (resp.places = 1))) 
  return resp
});

const city =  list_cities.map((resp) => {
  return {city: resp.name, places: resp.places}
});
console.log(city); // use this variable

相关问题