合并两个多维数组角

问题描述 投票:0回答:1

我正在尝试通过ID合并两个二维数组,但没有得到。

Services.ts

@Injectable({
 providedIn: 'root'
})
export class LancamentosService {

constructor(private http: HttpClient) { }
baseUrl = '/api/lancamentos'
baseurl2 = '/api/categorias'

getMouth(mouth:number):Observable<any>{
 return this.http.get<lancamentos>(`${this.baseUrl}?mes=${mouth}`)
 }
getCategorias(){
  return this.http.get<Categoria>(`${this.baseurl2}`)
 }

getAllData(){
  return this.http.get<lancamentos>(`${this.baseUrl}`)
 }
}

Appcomponent.ts

export class AppComponent implements OnInit {
lancamentos: any
total: Total
constructor(private services: LancamentosService){}

ngOnInit(){
  console.log(this.lancamentos);

  this.reloadData()
}
reloadData(){
  this.services.getAllData().subscribe((data:lancamentos)=> {this.lancamentos = data ; 
  console.log(this.lancamentos)},error => {console.log(error)})
 }

}

这些是数组:launchArray:

[{"id":1,"valor":13.3,"origem":"Uber","categoria":1,"mes_lancamento":1}]

categoryArray:

[{"id":1,"nome":"Transporte"}]

想法是,当类别ID为1时,应改用名称而且我无法做到这一点,我要做的是带有两个单独的数组

angular typescript multidimensional-array rxjs
1个回答
0
投票

您可以将两个可观察对象与forkJoin组合在一起,然后再通过map运算符进行转换结果

示例

const launchArray = rxjs.of([{
  "id": 1,
  "valor": 13.3,
  "origem": "Uber",
  "categoria": 1,
  "mes_lancamento": 1
}])

const categoryArray = rxjs.of([{
  "id": 1,
  "nome": "Transporte"
}])

rxjs.forkJoin(launchArray, categoryArray).pipe(
  rxjs.operators.map(combined => {
    const [data, categories] = combined;
    return data.map(pr => ({ ...pr,
      category: categories.find(cat => cat.id === pr.categoria).nome
    }))
  })
).subscribe(value => {
  console.log(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.