[英]How do I check if a particular object exist or not in a JavaScript array of objects?
How do I check if a particular object exist or not in a JavaScript array of objects?如何检查 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;
}
}
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:如果
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如果您不能依赖
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.