속성을 추가하려면 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' }
]