Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

javascript - How to check that object with same ID (or any other attribute ) exists in array of objects?

I have following array:

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"
                }
            ];

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.

In case that not = do push into existing array.

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

Thanks for any advice

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...