Computer >> Computer tutorials >  >> Programming >> Javascript

Set object property in an array true/false, whether the id matches with any id from another array of objects in JavaScript?


To set object property in an array true/false, whether the id matches with any id from another array of objects, you can use reduce() along with map().

Example

Following is the code −

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)

To run the above program, you need to use the below command −

node fileName.js.

Here, my file name is demo316.js.

Output

This will produce the following output −

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