如何将 json 数据格式化为数组格式,嵌套数组位于 {} 之类的对象中,打字稿中没有方括号

How to format json data to array format and nested arrays are in object like {} without square brackets in typscript

现在 return 来自其余 api 的数据为:

{ 
   "ProductID":1,
   "Category":[ 
      { 
         "CategoryID":1,
         "SubCategory":[ 
            { 
               "SubCategoryID":1,

            }
         ]
      }
   ]
}

我想将打字稿中操作的输出数据转换为:

[ 
   { 
      "ProductID":1,
      "Category":{ 
         "CategoryID":1,
         "SubCategory":{ 
            "SubCategoryID":1,
            `enter code here`
         }
      }
   }
]

我试过了

return this.restApi.getProductBin().subscribe((data: {}) => {
    const usersJson: any[] = Array.of(data);
})

下面是可以转换您需要的格式的代码:

const restructureProducts = (oldProds) => {
  let products = [];

  let newProd = {};
  if (oldProds.hasOwnProperty('ProductID'))
    newProd['ProductID'] = oldProds['ProductID'];

  if (
    oldProds.hasOwnProperty('Category') &&
    oldProds['Category'].length > 0 &&
    oldProds['Category'][0].hasOwnProperty('CategoryID')
  )
    newProd['Category'] = { CategoryID: oldProds['Category'][0]['CategoryID'] };
  if (oldProds['Category'][0].hasOwnProperty('SubCategory') && oldProds['Category'][0]['SubCategory'].length > 0)
    newProd['Category']['SubCategory'] = { SubCategoryID: oldProds['Category'][0]['SubCategory'][0]['SubCategoryID'] };

  products.push(newProd);
  
  return products;
}

let oldProds = {
  ProductID: 1,
  Category: [{
    CategoryID: 1,
    SubCategory: [{
      SubCategoryID: 1,
    }]
  }]
};

let products = restructureProducts(oldProds);
console.log(products);