How do I check if a particular object exist or not in a JavaScript array of objects?
// 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;
}
}
How to find an object in an array, or find out if it exists or not?
if name
property is unique you can simply check if there are any objects in array with the same 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);
If you can't rely on name
property and need to compare all properties, you may want to use isEqual
function from Lodash
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.