根据 Typescript 中的值对所有 JSON 键进行分组

Grouping all JSON key based on values in Typescript

我想根据值从单个 JSON 创建两个 JSON。下面考虑主要的 JSON 结构。

x = [
{id:"1",hobby:"videogames"},
{id:"1",hobby:"chess"},
{id:"2",hobby:"chess"},
{id:"3",hobby:"carrom"},
{id:"4",hobby:"videogames"},
{id:"4","hobby:"carrom"}
]

我想根据 ID 和 Hobby 创建两个 JSON。这样每个唯一 ID 都会有一个数组及其各自的爱好,并且每个独特的爱好都会有一个数组及其各自的提供者

ID =[
    { 
      1: [
          {hobby:"videogames"},
          {hobby:"chess"}
         ]
    },
    {
     2: [
         {hobby:"chess"}
        ]
    },
    {
     3: [
         {hobby:"carrom"}
        ]
    },
    {
     4: [
         {hobby:"videogames"},
         {hobby:"carrom"}
       ]
    }        
    ];

Hobby= [
        {
          videogames:[
                      {id:"1"},
                      {id:"4"}
                     ]
        },
        {
          chess:[
                 {id:"2"}
                ]
        },
        {
          carrom:[
                  {id:"3"},
                  {id:"4"}
                 ]
        } 
      ]

你需要应用array.reduce函数来构建一个字典,其中idshobbies是键,然后运行 array.map将这样的字典转换成多个数组条目:

let x = [
   {id:"1",hobby:"videogames"},
   {id:"1",hobby:"chess"},
   {id:"2",hobby:"chess"},
   {id:"3",hobby:"carrom"},
   {id:"4",hobby:"videogames"},
   {id:"4",hobby:"carrom"}
];

let grouped = x.reduce((acc, cur) => {
  let {id, ...rest} = cur;
  if(!acc[id]){
     acc[id] = [];
  }
  acc[id].push(rest);
  return acc;
}, {});

let result = Object.entries(grouped).map(([key, value]) => ({[key]: value}))

console.log(result);

您可以尝试使用数组 reduce 函数。我还要说,在对象内部具有 hobbyid 属性是多余的,因为变量名称已经暗示了属性中包含的数据的含义。

var x = [
  {id:"1",hobby:"videogames"},
  {id:"1",hobby:"chess"},
  {id:"2",hobby:"chess"},
  {id:"3",hobby:"carrom"},
  {id:"4",hobby:"videogames"},
  {id:"4",hobby:"carrom"}
];

var ID = x.reduce((acc, curr) => {
  acc[curr.id] = acc[curr.id] || [];
  acc[curr.id].push(curr.hobby);
  return acc;
}, Object.create(null));

var Hobby = x.reduce((acc, curr) => {
  acc[curr.hobby] = acc[curr.hobby] || [];
  acc[curr.hobby].push(curr.id);
  return acc;
}, Object.create(null));

console.log('ID: ', ID);
console.log('Hobby: ', Hobby);
.as-console-wrapper { max-height: 100% !important; top: 0; }