如何检查具有相同ID

如何检查具有相同ID

本文介绍了如何检查具有相同ID(或任何其他attribute)的对象是否存在于对象数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组:

var array = [
                {
                    "milestoneTemplate": {
                        "id": "1",
                        "name": "TEST1"
                    },
                    "id": "1",
                    "date": "1416680824",
                    "type": "ETA",
                    "note": "Note",
                    "color": "66FF33"
                },
                {
                    "milestoneTemplate": {
                        "id": "2",
                        "name": "Test 2"
                    },
                    "id": "2",
                    "date": "1416680824",
                    "type": "ATA",
                    "note": "Note 22",
                    "color": "66FF00"
                }
            ];

现在我想在forEach循环中检查该对象(在函数的参数中传递的对象)是否存在于其ID的数组中.

And now i would like to check in forEach loop that object (which is passed in param of the function) is existing in array by his ID.

如果not =不要推入现有数组.

In case that not = do push into existing array.

arrayOfResults.forEach(function(entry) {
                if(entry != existingInArrayByHisId) {
                array.push(entry);
}
        });

谢谢您的建议

推荐答案

您可以创建一个辅助函数,该函数检查数组是否包含具有匹配属性值的项,如下所示:

You could create a helper function thats checks if an array contains an item with a matching property value, something like this:

function checkForMatch(array, propertyToMatch, valueToMatch){
    for(var i = 0; i < array.length; i++){
        if(array[i][propertyToMatch] == valueToMatch)
            return true;
    }
    return false;
}

然后可以像这样使用它:

which you can then use like so:

arrayOfResults.forEach(function (entry) {
    if (!checkForMatch(array, "id", entry.id)) {
        array.push(entry);
    }
});

这篇关于如何检查具有相同ID(或任何其他attribute)的对象是否存在于对象数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:25