如何使用 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' ] } ]
广告