要在数组true / false中设置对象属性,无论id是否与另一个对象数组中的任何id匹配,都可以reduce()与一起使用map()。
以下是代码-
let
firstDetails=[{"studentId":101,"studentName":"John"},{"studentI d":102,"studentName":"David"},{"studentId":103,"studentName":"B ob"}]
let
secondDetails=[{"studentId":101,"studentName":"Robert"},{"stude ntId":109,"studentName":"Mike"},{"studentId":103,"studentName": "Adam"}]
const obj = secondDetails.reduce((o, v) => (o[v.studentId] = true, o), {})
const output = firstDetails.map(v => ({ ...v, matchingResult: obj[v.studentId] || false}))
console.log(output)要运行上述程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo316.js。
输出结果
这将产生以下输出-
PS C:\Users\Amit\javascript-code> node demo316.js
[
{ studentId: 101, studentName: 'John', matchingResult: true },
{ studentId: 102, studentName: 'David', matchingResult: false },
{ studentId: 103, studentName: 'Bob', matchingResult: true }
]