繁体   English   中英

根据 typescript 中的数组中的 2 个或更多值获取不同的基础

[英]get distinct base on 2 or more Values from array in typescript

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

在此处输入图像描述

我想要这个图案:

在此处输入图像描述

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

工作TS 操场

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM