1

I am developing a new angular 8 project where in my component, I get json data from 2 different services. the data is array of objects. I want to join the objects in the array and post it back to the database.

here is the code

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(){

}


}

How can I combine this data together and map the salaries to correct person so it goes into a new array like this:

personWithSalary = [
    {name: "john", id: 1, joined: "2018", salary: 3000},
    {name: "sarah", id: 2, joined: "2019", salary: 5000}
]
3
  • however, your salary already has the desired data Commented Feb 23, 2020 at 18:43
  • It has the desired data but the first array will have more properties than the second array, I have just made up this data for guidance. Commented Feb 23, 2020 at 18:46
  • I have edited the question so it can make more sense. Commented Feb 23, 2020 at 18:53

3 Answers 3

1

You can use Map collection to have O(1) while mapping person array:

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

An example:

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);

Sign up to request clarification or add additional context in comments.

1 Comment

@Chris I am glad that it helped to you:)
1

You could use reduce and the spread operator to merge your arrays:

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;
},[])

Comments

0
    personWithSalary = person.map(p => {
        p['salary'] = salary.find(s =>s.name === p.name && s.id === p.id).salary;
        return p;
    })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.