向数组和对象数组中的公共项添加属性 - JavaScript?
javascriptweb developmentfront end technology更新于 2024/4/20 22:03:00
要添加属性,请使用 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' } ]