从typescript中的数组获取基于2个或多个值的非重复

nukf8bse  于 2023-01-18  发布在  TypeScript
关注(0)|答案(1)|浏览(126)

我有一个如下所示的数组。

我想要此图案:

**我想获取不同的“CityRef”和“City”。**然后查找与之关联的所有项目。

2w2cym1i

2w2cym1i1#

工作TSPlayground。

interface GroupedItemsByCity {
  cityRef: number
  cityName: string,
  items: Array<{
    id: number,
    itemName: string
  }>
}

const groupedObject = returnObject.reduce<GroupedItemsByCity[]>((groupedArray, item) => {
    // New slimmer item to push later
    let refinedItem = {
        id: item.id,
        itemName: item.itemName
    }

    const matchedCity = groupedArray.find(city => city.cityRef === item.cityRef); // Check if the new structure already has a matching parent city for current item.
    if (matchedCity) {
        // If it does, push the item onto the existing city object.
        matchedCity.items.push(refinedItem)
        return groupedArray
    }

    // If it doesn't set up a new city and add the item to it
    groupedArray.push({
        cityRef: item.cityRef,
        cityName: item.cityName,
        items: [refinedItem]
    })

    return groupedArray
}, [])

console.log(groupedObject)

相关问题