0

我一直在尝试将 JSON 对象中的嵌套数组数据转换为 Typescript 中的嵌套 JSON 对象。这是输入打字稿时从rest api返回的数据:

嵌套数组包含方括号。

data={ "ID":29614,"Ratio":8,"UOM":"IN", "manufacturers": [{ "manufacturerName": "john", "categories": [{ "categoryName": "Beverage", "products": [{ "uid": "567", "productID": 130927, "name": "After Shocks Popping Candy 1.06"}] }] } , { "manufacturerName": "Dan", "categories": [{ "categoryName": "Organization", "products": [{ "uid": "65", "productID": 5656, "name": "After Shocks Popping Candy 2.06"}] }] } ] }


Format I need is:

data=[{ "ID":29614,"Ratio":8,"UOM":"IN", "manufacturers": { "manufacturerName": "john", "categories": { "categoryName": "Beverage", "products": { "uid": "567", "productID": 130927, "name": "After Shocks Popping Candy 1.06"} } } , { "manufacturerName": "Dan", "categories": { "categoryName": "Organization", "products": { "uid": "65", "productID": 5656, "name`enter code here`": "After Shocks Popping Candy 2.06"} } } }]

Output nested array should remove square brackets.

I have tried this as

public gridData: any[];
//gridData  for bind Kendo grid 

return this.restApi.getProductBin().subscribe((data: {}) => {
this.gridData = Array.of(data); //convert to array
}

4

2 回答 2

1

如果您只想删除方括号,您可以将 JSON 字符串化,使用正则表达式删除所有 '[' 和 ']',然后将其解析回 JSON 对象:

getNoArrayJSON(data: {}): {} {
    let dataString = JSON.stringify(data);
    dataString = dataString.replace(/(\[)|(\])/g, "");
    return JSON.parse(dataString);
});

我不会这样做,除非你知道你正在处理的响应中的数组永远只有 1 的大小。

工作示例:RegEx 删除数组

如果您打算将该结果放入数组中,let newData = [getNoArrayJSON(data)];并且格式将与您所需的输出完全匹配。

于 2019-12-30T16:48:28.537 回答
0

试试这样:

  output = [];

  constructor() {
    this.output.push({
      ID: this.data.ID,
      Ratio: this.data.Ratio,
      UOM: this.data.UOM,
      manufacturers: {
        manufacturerName: this.data.manufacturers[0].manufacturerName,
        categories: {
          categoryName: this.data.manufacturers[0].categories[0].categoryName,
          products: this.data.manufacturers[0].categories[0].products[0]
        }
      }
    });
  }

工作演示

于 2019-12-30T15:31:32.690 回答