Update array of objects with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say the following are our array of objects −

var studentDetails = [
   { firstName: "John", listOfSubject: ['MySQL', 'MongoDB']},
   {firstName: "David", listOfSubject: ['Java', 'C']
}]

We need to add the following in the already created array of objects −

{firstName: "Bob", listOfSubject: ['JavaScript']};

Example

var studentDetails = [
   { firstName: "John", listOfSubject: ['MySQL', 'MongoDB']},
   {firstName: "David", listOfSubject: ['Java', 'C']}];
   updateThisObject = {firstName: "Bob", listOfSubject: ['JavaScript']};
   function forLoopExample(studentObjects, updateObj){
   for(var index = 0;index < studentObjects.length; index++) {
      if(updateObj.listOfSubject.join("") ===
         studentObjects[index].listOfSubject.join("")) {
         studentObjects[index] = updateObj;
         return;
      }
   }
   studentObjects.push(updateObj);
}
forLoopExample(studentDetails, updateThisObject);
console.log(studentDetails);

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

node fileName.js.

Here, my file name is demo100.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo100.js
[
   { firstName: 'John', listOfSubject: [ 'MySQL', 'MongoDB' ] },
   { firstName: 'David', listOfSubject: [ 'Java', 'C' ] },
   { firstName: 'Bob', listOfSubject: [ 'JavaScript' ] }
]
raja
Published on 07-Sep-2020 12:11:18
Advertisements