【问题标题】:Javascript match two arrays by idJavascript 通过 id 匹配两个数组
【发布时间】:2022-11-02 16:30:38
【问题描述】:

目标是通过 id 匹配两个数组。我需要检查stopId 是否在infotimes 数组中并组合匹配的数组。

找出 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


【解决方案1】:

试试这个:

const result = info.map((item) => {
  const time = times.find((time) => time.stopId === item.stopId)
   return {
     ...item,
     time: time ? time.time : null
   }
})

【讨论】:

    【解决方案2】:

    附上一个工作示例

    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) => {
        let temp = { ...item
        };
        times.forEach((el) => {
          if (item.stopId === el.stopId) {
            temp = { ...temp,
              ...el
            };
          }
        })
        final.push(temp);
      })
      console.log(final);
    }
    
    res()

    【讨论】:

      【解决方案3】:

      使用includes,您正在比较的对象时间停止标识物品.您必须先选择时间的 stopId。您可以使用运算符 find 例如:

      info.forEach((item) => {
           if (times.find(t => t.stopId === item.stopId)) {
             final.push({  })
           }
        })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-11
        • 2020-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-06
        • 2021-12-27
        • 2018-07-10
        相关资源
        最近更新 更多