簡體   English   中英

我如何計算一個數組中的屬性出現在另一個數組中的次數,以及 map 匹配新數組的次數?

[英]How can I count and the number of times a property from one array appears in another, and map the matches to a new array?

我正在嘗試將 fk_city 與“list_cities”中 object 的 $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',
  },
];

我基本上是在嘗試計算每個城市的地點數量,但到目前為止我無法將其添加到 output 一個僅顯示的新數組:

[
    {city: "Pittsburg", places: "2"}
    {city: "Los Angeles", places: "1"}
]  

我試過將 list_cities 中的 $id 與 list_places 中的屬性 fk_city 匹配,但我不知道如何計算相同的 $id 出現在 places 數組中的次數。 這應該是一個外鍵關系,但我使用的后端只能像這樣從端點提供 id 的原始數據,所以我需要手動 map $id。

任何幫助表示贊賞! 謝謝!

嘗試循環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);

如果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);

此代碼對我有用,請檢查它是否可以幫助您

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM