如何根据特定条件存储json数据

时间:2019-03-13 17:07:15

标签: angular

数据的外观

0: {id: 1, name: "strter", subscriber: 2500, amount: 0}
1: {id: 2, name: "Pro_2500", subscriber: 2500, amount: 10}
2: {id: 3, name: "Pro_5k", subscriber: 5000, amount: 20}
3: {id: 4, name: "Pro_10k", subscriber: 10000, amount: 30}
4: {id: 14, name: "Enterprise_2500", subscriber: 2500, amount: 100}
5: {id: 15, name: "Enterprise_5k", subscriber: 5000, amount: 110}
6: {id: 16, name: "Enterprise_10k", subscriber: 10000, amount: 120}

我已经声明了3个属性starter pro和enterprise。以上所有数据均在属性allPlans中 我希望根据名称是pro,starter还是enterprise将所有数据存储到各自的属性中。因此,所有名称为pro的数据都应存储在pro: any

export class XComponent implements OnInit {
allPlans: any;
starter: any;
pro: any;
enterprise: any;

 constructor(private activatedRoute: ActivatedRoute) { 
    activatedRoute.data.subscribe((res)=>{
      this.allPlans = res.plansresolve.data;
    });
  }
}

我尝试过了,它会打印所有的

this.pro = this.allPlans.find((x: any)=>{ x.name === "Pro_"; console.log(x.name) })

3 个答案:

答案 0 :(得分:0)

constructor(private activatedRoute: ActivatedRoute) { 
activatedRoute.data.subscribe((res)=>{
  this.allPlans = res.plansresolve.data;
  this.allPlans.forEach(p => {
       this.pro = this.allPlans.filter((x: any)=> x.name.includes("Pro_"));
       this.starter = this.allPlans.filter((x: any)=> x.name.includes("starter"));
       this.enterprise = this.allPlans.filter((x: any)=> x.name.includes("Enterprise_"));

   });
});

}

switch情况也最好

答案 1 :(得分:0)

this.pro = this.allPlans.filter((x: any)=>{ x.name.indexOf("Pro_")>-1 });

答案 2 :(得分:0)

我将使用RXJS映射运算符来转换数据。

stackblitz example

import { Component, OnInit } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {

  name = 'Angular';
  public data = {allPlans: [
    {id: 1, name: "strter", subscriber: 2500, amount: 0},
    {id: 2, name: "Pro_2500", subscriber: 2500, amount: 10},
    {id: 3, name: "Pro_5k", subscriber: 5000, amount: 20},
    {id: 4, name: "Pro_10k", subscriber: 10000, amount: 30},
    {id: 14, name: "Enterprise_2500", subscriber: 2500, amount: 100},
    {id: 15, name: "Enterprise_5k", subscriber: 5000, amount: 110},
    {id: 16, name: "Enterprise_10k", subscriber: 10000, amount: 120},
  ],
  starter: [],
  pro: [],
  enterprise: []};

  xdata: BehaviorSubject<any> = new BehaviorSubject(this.data);

  result: [];

  ngOnInit() {
    this.xdata
    .pipe(
      map( d => {
        d.starter = d.allPlans.filter(f => f.name === 'strter');
        d.pro = d.allPlans.filter(f => f.name.substring(0, 3) === 'Pro');
        d.enterprise = d.allPlans.filter(f => f.name.substring(0, 10) === 'Enterprise');
        return d;
        })
    ).subscribe( d => {
      this.result = d;
    });
  }
}