var enterprise = [
{
name: 'SULU',
species: ' '
},
{
name: 'KIRK',
species: 'Human'
}
];
var yorktown = [
{
name: 'BEN',
species: 'Human'
},
{
name: 'DEMORA',
species: 'Human'
},
{
name: 'SULU',
species: 'Human'
}
];
이런식으로 배열 안에 객체 비교를 어떻게 해야할까 JavaScript의 object는 참조에 의해 할당되고 복사 되기 때문에 ==,===,object.is()를 사용하여 같은 값을 지닌 객체인지 비교할 수 없다. 객체 자체가 아닌 각각의 변수들이 저장하고 있는 객체의 참조를 비교하기 때문에 같은 값의 객체가 있어도 false를 리턴한다. 따라서 중첩된 for문이나 fitter,reduce도 사용 불가하다.
let array = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}];
let obj = {id: 2, name: 'Bob'};
let array = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}];
let obj = {id: 2, name: 'Bob'};
let result = array.find(function(element) {
return element.id === obj.id && element.name === obj.name;
});
if (result) {
console.log('The object is in the array.');
}
let array = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}];
let obj = {id: 2, name: 'Bob'};
let result = array.find(function(element) {
return element.id === obj.id && element.name === obj.name;
});
if (result) {
console.log('The object is in the array.');
}