【发布时间】:2022-11-02 16:30:38
【问题描述】:
目标是通过 id 匹配两个数组。我需要检查stopId 是否在info 和times 数组中并组合匹配的数组。
找出 id 是否匹配的正确检查应该是什么?我附上了一个例子,我试图使用includes 来实现。
你能给我一个建议吗?
const info = [
{
stopId: 1,
name: "N1"
},
{
stopId: 2,
name: "N2"
},
{
stopId: 3,
name: "N3"
}
]
const times = [
{
stopId: 1,
time: "T1"
},
{
stopId: 3,
time: "T2"
}
]
// Expected
// [
// {
// stopId: 1,
// name: "123",
// time: "T1"
// },
// {
// stopId: 2,
// name: "123"
// },
// {
// stopId: 3,
// name: "123",
// time: "T2"
// }
// ]
const res = () => {
const final = [];
info.forEach((item) => {
if (times.includes(item.stopId)) { // How to check if stopId matches
final.push({ })
}
})
}
console.log(res())
【问题讨论】:
-
const combined = info.map(i => ({ ...i, ...times.find(t => t.stopId === i.stopId) }))
标签: javascript