I have two arrays:
const people = [{id:1, name:"John"}, {id:2, name:"Alice"}];
const address = [{id:1, peopleId: 1, address: "Some street 1"}, {id:2, peopleId: 2, address: "Some street 2"}]
How can I filter over this two arrays and get one like this:
const fullData = [{id: 1, name: "John", address: "Some street 1"}, {id: 2, name: "Alice", address: "Some street 2"}]
You can try this.
With the help of map() and find()
const people = [{id:1, name:"John"}, {id:2, name:"Alice"}];
const address = [{id:1, peopleId: 1, address: 'Some street 1'}, {id:2, peopleId: 2, address: 'Some street 2'}]
let op = people.map((e,i)=>{
let temp = address.find(element=> element.id === e.id)
if(temp.address) {
e.address = temp.address;
}
return e;
})
console.log(op);
Like this:
const persons = [{id:1, name: 'John'}, {id:2, name: 'Alice'}]
const addresses = [{id:1, peopleId: 1, address: 'Some street 1'}, {id:2, peopleId: 2, address: 'Some street 2'}]
const result = persons.map(person => {
const addressItem = addresses.find(address => address.peopleId === person.id)
person.address = addressItem
? addressItem.address
: null
return person
})
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With