向数组和对象数组中的公共项添加属性 - JavaScript?
javascriptweb developmentfront end technology更新于 2026/1/6 3:24:17
要添加属性,请使用 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' }
]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

