如何在使用HTTP响应时正确分组数据?

时间:2017-10-11 08:39:15

标签: json angular rxjs observable rxjs5

这是iam想要实现的目标,我想在Array JSON中groupBy product_category但我的数组JSON是嵌套的,如下所示:

[
    {
        "result": "success",
        "data": [
            {
                "product_id": 17,
                "product_name": "KLO-101",
                "parent_category": "Juicer"
            },
            {
                "product_id": 42,
                "product_name": "CRO-528",
                "parent_category": "Vacuum Cleaner"
            },
            {
                "product_id": 15,
                "product_name": "KLC-127",
                "parent_category": "Juicer"
            },
            {
                "product_id": 41,
                "product_name": "CRO-3120-WD",
                "parent_category": "Vacuum Cleaner"
            }
        ]
    }
]

我想要构建的json是什么,下面是我手动编写的JSON插图:

[{
    'Vacuum Cleaner' : 
           [{
                "product_id": 41,
                "product_name": "CRO-3120-WD",
                "parent_category": "Vacuum Cleaner"
            },
            {
                "product_id": 42,
                "product_name": "CRO-528",
                "parent_category": "Vacuum Cleaner"
            }],
   'Juicer' : 
            [{
                "product_id": 17,
                "product_name": "KLO-101",
                "parent_category": "Juicer"
                 },
            {
                "product_id": 15,
                "product_name": "KLC-127",
                "parent_category": "Juicer"
            }]
}]

从我读到的内容,在stackoverflow的某个地方,它写的JSON数据可以使用map()进行分组.groupBy()在我的代码中,它看起来像这样:

app.service.ts:

getProductService(): Observable<any> {
    return this.http
        .post(global.server + "/product", this.options)
        .map(a=> a.json().data)
        .groupBy(
            a=>a.parent_category,
            a=>a
        )
        .catch(this.handleError);
}

这是我的app.component.ts:

  getProduct() {
    this.appService.getProductService().subscribe(
      result => {
        console.log(result);
        this.dataProduct = result[0].data;
      },
      error => this.errorMessage = <any>error
    );
  }

但我收到错误,&#39; a未定义&#39;如何正确使用.groupBy()?我使用的角度版本是角度4

UPDATE !!!

这是我用马丁回答更新后的代码,但我仍然无法弄清楚,因为我必须从REST API中提取JSON数据,代码无法检测到&#39 ; parent_category&#39;,下面是我的代码

app.component.ts

dataProduct : any;

      getProduct() {
        this.appService.getProductService().subscribe(
          result => {
            this.dataProduct = result[0].data;
          },
          error => this.errorMessage = <any>error
        );

        Observable.of(this.dataProduct)
          .mergeMap(array => array) // unpack into single emissionns (or mergeAll() but it's broken in RxJS 5.4)
          .groupBy(item => item.parent_category)
          .mergeMap(observable => observable
            .toArray()
            .map(results => (this.dataProduct = { [results[0].parent_category]: results }))
          )
          .toArray()
          .subscribe(console.log);

          console.log(JSON.stringify(this.dataProduct));
      }

我收到了错误

  

[ts]属性&#39; parent_category&#39;类型&#39; {}&#39;

上不存在

enter image description here

3 个答案:

答案 0 :(得分:0)

在角度1中,这就是我的方式

var inputdata = [
{
    "result": "success",
    "data": [
        {
            "product_id": 17,
            "product_name": "KLO-101",
            "parent_category": "Juicer"
        },
        {
            "product_id": 42,
            "product_name": "CRO-528",
            "parent_category": "Vacuum Cleaner"
        },
        {
            "product_id": 15,
            "product_name": "KLC-127",
            "parent_category": "Juicer"
        },
        {
            "product_id": 41,
            "product_name": "CRO-3120-WD",
            "parent_category": "Vacuum Cleaner"
        }
    ]
}];

var grouped = _(inputdata[0].data).groupBy(function (d) {
    return d.parent_category;
});

var finalArray = _.mapObject(grouped, function (value, key) {
    return value;
});

答案 1 :(得分:0)

groupBy是一个发出Observables的RxJS运算符。换句话说,它返回一个Observable发出其他Observable(所谓的&#34;高阶Observable&#34;)。您可以更轻松地仅使用map()并在那里转换数据,但如果您想使用groupBy,则需要进行一些调整以确保内部Observable在您通过之前完成它到结果对象:

const data = [
    {
        "product_id": 17,
        "product_name": "KLO-101",
        "parent_category": "Juicer"
    },
    {
        "product_id": 42,
        "product_name": "CRO-528",
        "parent_category": "Vacuum Cleaner"
    },
    {
        "product_id": 15,
        "product_name": "KLC-127",
        "parent_category": "Juicer"
    },
    {
        "product_id": 41,
        "product_name": "CRO-3120-WD",
        "parent_category": "Vacuum Cleaner"
    }
];

Observable.of(data)
    .mergeMap(array => array) // unpack into single emissionns (or mergeAll() but it's broken in RxJS 5.4)
    .groupBy(item => item.parent_category)
    .mergeMap(observable => observable
        .toArray()
        .map(results => ({ [results[0].parent_category] : results }))
    )
    .toArray()
    .subscribe(console.log);

打印:

[ { Juicer: [ { product_id: 17,
       product_name: 'KLO-101',
       parent_category: 'Juicer' },
     { product_id: 15,
       product_name: 'KLC-127',
       parent_category: 'Juicer' } ] },
  { 'Vacuum Cleaner': [ { product_id: 42,
       product_name: 'CRO-528',
       parent_category: 'Vacuum Cleaner' },
     { product_id: 41,
       product_name: 'CRO-3120-WD',
       parent_category: 'Vacuum Cleaner' } ] 
} ]

答案 2 :(得分:0)

我想我必须实现lodash,因为我真的很难以观察的方式,我真的无法理解它,所以我决定使用lodash方式,它很简单,所以这是我的代码如何正确分组JSON数据。我必须导入已经包含在我的项目中的lodash,如果你的node_modules中没有lodash,你必须npm安装它

import * as _ from 'lodash';

  getProduct() {
    this.appService.getProductService().subscribe(
      result => {
        this.dataTest = result;

        let datas = this.dataTest;

        this.dataProduct = _(datas)
        .groupBy(data => data.parent_category)
        .map((datas, category) => ({ category, datas }))
        .value();

      },
      error => this.errorMessage = <any>error
    );

我只需要将JSON数据循环到&#34;数据&#34;在HTML中使用* ngFor