使用JavaScript更新对象数组?
假设以下是我们的对象数组-
var studentDetails = [ { firstName: "John", listOfSubject: ['MySQL', 'MongoDB']}, {firstName: "David", listOfSubject: ['Java', 'C'] }]
我们需要在已创建的对象数组中添加以下内容:
{firstName: "Bob", listOfSubject: ['JavaScript']};
示例
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);
要运行上述程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo100.js。
输出结果
这将产生以下输出-
PS C:\Users\Amit\JavaScript-code> node demo100.js [ { firstName: 'John', listOfSubject: [ 'MySQL', 'MongoDB' ] }, { firstName: 'David', listOfSubject: [ 'Java', 'C' ] }, { firstName: 'Bob', listOfSubject: [ 'JavaScript' ] } ]