3

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"}]
1

4 Answers 4

18

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

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

4 Comments

I'm not entirely sure but I think the matcher in address is peopleId, whereas id is just the address row identifier.
@NicholasKyriakides well id is meant to be used in that way. don't know how op has used.
What if a person doesn't have an address? Your map will throw a TypeError, no?
@NicholasKyriakides op didn't asked.anyways added a check for that.
4

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)

Comments

0

How to map two address with peopleId 2

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'},{id:3, peopleId: 2, address: 'Some street 3'}]

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)

Comments

0

You can use reduce to do that,

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'}]


const res = people.reduce((acc, curr) => {
  const index = address.findIndex(item => item.peopleId === curr.id);
  if(index > -1) {
    curr.address = address[index].address;
  }
  
  acc.push(curr);
  return acc;
}, []);
console.log(res);

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.