Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Update array of objects with JavaScript?
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' ] }
]Advertisements