如何检查对象的JavaScript数组中是否存在特定对象?
// Main array of objects
var dailogMappingData = [
{
"name": "AgglomerativeCluster",
"size": 3938
}, {
"name": "CommunityStructure",
"size": 3812
}, {
"name": "HierarchicalCluster",
"size": 6714
}
];
// search object to find in the above array is exist or not:
var findObj = {
"name": "CommunityStructure",
"size": 3812
};
var m, n;
for (m = 0; m < this.dailogMappingData.length; m++) {
for (n = 0; n < mapKeys.length; n++) {
if (this.dailogMappingData[m][mapKeys[n]] === newObj[mapKeys[n]]) {
isInArray = true;
} else {
isInArray = false;
}
}
if (isInArray) {
break;
}
}
如何在数组中查找对象,或查找对象是否存在?
答案 0 :(得分:0)
如果name
属性是唯一的,则可以简单地检查数组中是否有相同名称的对象:
var dailogMappingData = [{
"name": "AgglomerativeCluster",
"size": 3938
}, {
"name": "CommunityStructure",
"size": 3812
}, {
"name": "HierarchicalCluster",
"size": 6714
}];
var findObj = {
"name": "CommunityStructure",
"size": 3812
};
const isInArray = dailogMappingData.some(item => item.name === findObj.name);
console.log(isInArray);
如果您不能依赖name
属性,而需要比较所有属性,则可能要使用Lodash中的isEqual
函数
var dailogMappingData = [{
"name": "AgglomerativeCluster",
"size": 3938
}, {
"name": "CommunityStructure",
"size": 3812
}, {
"name": "HierarchicalCluster",
"size": 6714
}];
var findObj = {
"name": "CommunityStructure",
"size": 3812
};
const isInArray = dailogMappingData.some(item => _.isEqual(findObj, item));
console.log(isInArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>