要添加属性,请使用map()
。假设以下是我们的数组-
const firstname = ['John', 'David', 'Bob'];
以下是我们的对象数组-
const studentDetails = [ { firstname: 'Carol', marks: 78 }, { firstname: 'Mike', marks: 89 }, { firstname: 'Bob', marks: 86 } ];
例
以下是代码-
const firstname = ['John', 'David', 'Bob']; const studentDetails = [ { firstname: 'Carol', marks: 78 }, { firstname: 'Mike', marks: 89 }, { firstname: 'Bob', marks: 86 } ]; const data = new Set(firstname); const result = studentDetails.map(tmpObject => { if (data.has(tmpObject.firstname)) tmpObject.isPresent ="This is present"; else tmpObject.isPresent = "This is not present"; return tmpObject; }); console.log(result);
要运行以上程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo219.js。
输出结果
输出如下-
PS C:\Users\Amit\JavaScript-code> node demo219.js [ { firstname: 'Carol', marks: 78, isPresent: 'This is not present' }, { firstname: 'Mike', marks: 89, isPresent: 'This is not present' }, { firstname: 'Bob', marks: 86, isPresent: 'This is present' } ]