Finding content of arrays on the basis of specific property in JavaScript?


For this, you can use find() along with a map(). Let’s say we have student records with name, rollno and subject.

Example

var firstObject=
[
   { "FirstName": "David", "RollNo": "105", "Subject": "MongoDB" },
   { "FirstName": "Mike", "RollNo": "110", "Subject": "JavaScript"}
];
var secondObject= [
   { "FirstName": "Bob", "RollNo": "101", "Subject": "Java" },
   { "FirstName": "John", "RollNo": "110", "Subject": "MySQL" }
];
var output =
firstObject.map(first=>(secondObject.find(second=>second.RollNo==first.R
ollNo) || first));
console.log(output);

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

node fileName.js

Here, my file name is demo33.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo33.js
[
   { FirstName: 'David', RollNo: '105', Subject: 'MongoDB' },
   { FirstName: 'John', RollNo: '110', Subject: 'MySQL' }
]

Updated on: 01-Sep-2020

79 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements