如何检查对象的JavaScript数组中是否存在特定对象?

时间:2019-07-25 11:36:31

标签: javascript arrays object find

如何检查对象的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;
    }
}

如何在数组中查找对象,或查找对象是否存在?

1 个答案:

答案 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>