我有两个数组:
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 fullData = [{id: 1, name: 'John', address: 'Some street 1'}, {id: 2, name: 'Alice', address: 'Some street 2'}]
答案 0 :(得分:2)
您可以尝试一下。
借助map()
和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);
答案 1 :(得分:1)
赞:
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)
答案 2 :(得分:0)
如何使用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)
答案 3 :(得分:0)
您可以使用reduce来做到这一点,
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);