【问题标题】:Combine two JSON Array of Objects Coming from Different Http Service in Angular 8在Angular 8中组合来自不同Http服务的两个JSON对象数组
【发布时间】:2020-02-23 18:35:23
【问题描述】:

我正在开发一个新的 Angular 8 项目,在我的组件中,我从 2 个不同的服务获取 json 数据。 数据是对象数组。我想加入数组中的对象并将其发送回数据库。

这里是代码

import { Component , OnInit} from '@angular/core';

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


// data comes from Persons Service
person = [
{name: "john", id: 1, joined: "2018"},
{name: "sarah", id: 2, joined: "2019"}
]

// data comes from salary Service
salary = [
{name: "john", id: 1, salary: 3000},
{name: "sarah", id: 2, salary: 5000}
]


personWithSalary;


ngOnInit(){

}


}

我如何将这些数据组合在一起并将工资映射到正确的人,以便它进入一个新的数组,如下所示:

personWithSalary = [
    {name: "john", id: 1, joined: "2018", salary: 3000},
    {name: "sarah", id: 2, joined: "2019", salary: 5000}
]

【问题讨论】:

  • 但是,您的salary 已经拥有所需的数据
  • 它有想要的数据,但是第一个数组比第二个数组有更多的属性,我只是为了指导而编了这个数据。
  • 我已经编辑了这个问题,让它更有意义。

标签: arrays json angular object


【解决方案1】:

您可以使用Map 集合来拥有O(1),同时映射person 数组:

const uniqueSalaries = new Map(salary.map(s => [s.id, s]));
const result = person.map(({id, ...rest}) => ({...rest, ...uniqueSalaries.get(id)}));

一个例子:

let person = [
    {name: "john", id: 1, joined: "2018"},
    {name: "sarah", id: 2, joined: "2019"}
]    
let  salary = [
    {name: "john", id: 1, salary: 3000},
    {name: "sarah", id: 2, salary: 5000}
];    

const uniqueSalaries = new Map(salary.map(s => [s.id, s]));
const result = person.map(({id, ...rest}) => ({...rest, ...uniqueSalaries.get(id)}));
console.log(result);

【讨论】:

  • @Chris 我很高兴它对你有所帮助:)
【解决方案2】:

您可以使用reduce 和扩展运算符来合并您的数组:

const personWithSalary = this.person.reduce((result,person) => {
      const salary = this.salaries.find(sal => sal.id === person.id);
      if(salary){
        result.push({...person,...salary});
      }
      return result;
},[])

【讨论】:

    【解决方案3】:
        personWithSalary = person.map(p => {
            p['salary'] = salary.find(s =>s.name === p.name && s.id === p.id).salary;
            return p;
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      • 2020-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多