简体   繁体   English

如何使用 Typescript 将 JSON 数据转换为键值对

[英]How to convert the JSON data into Key Value Pair using Typescript

A JSON data has 2 arrays (categories & applets) as shown below.一个 JSON 数据有 2 个 arrays(类别和小程序),如下所示。 Each applet can belong to many categories as per the data.根据数据,每个小程序可以属于许多类别。

categories = ['Investments', 'Operations', 'Performance'];

applets = [
  {
    name: 'Performance Snapshot',
    categories: ['Performance'],
  },
  {
    name: 'Commitment Widget',
    categories: ['Investments'],
  },
  {
    name: 'CMS',
    categories: ['Investments', 'Performance'],
  },
];

I need to convert that JSON data to use them as category wise as shown below.我需要将 JSON 数据转换为按类别使用它们,如下所示。 How to do this in Typescript??如何在 Typescript 中做到这一点?

categories = [
    {
       'name': 'Performance',
       'applets': ['CMS', 'Performance Snapshot']
    },
    {
        'name' : 'Investments',
        'applets' : ['Commitment Widget', 'CMS']
    },
    {
        'name' : 'Operations',
        'applets' : []
    }
]
    const result = categories.map((category) => {
         const temp = {};
         const filteredApplets = applets.filter((ele) => 
                      ele.categories.includes(category)).map(({name}) => name);
         temp['name'] = category;
         temp['applets'] = filteredApplets;
         return temp;
   })

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

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