检查嵌套数组中是否存在值

时间:2015-06-09 03:02:04

标签: javascript arrays nested

如果我有这样的嵌套数组:

"localValues" : [
    {
        "localValId" : "e3rQACssGkfp9zsue",
        "localProductCode" : "271102502",
        "localMembersPrice" : 7814.090000000001,
        "localProductDescription" : "11R225 146/143L H DUN SP384 FM        TL",
        "fetPr" : "29.39",
        "invPrice" : "353.85"
    },
    {
        "localValId" : "NxtmZngRpGY56grkW",
        "localProductCode" : "290132910",
        "localMembersPrice" : "300",
        "localProductDescription" : "215/70R16 99S     DUN GRNDTRK ST20 BSWTL",
        "fetPr" : "",
        "invPrice" : "136.72"
    },
    {
        "localValId" : "WXLiCMJMixndtQtqZ",
        "localProductCode" : "271102502",
        "localMembersPrice" : "444",
        "localProductDescription" : "11R225 146/143L H DUN SP384 FM        TL",
        "fetPr" : "29.39",
        "invPrice" : "353.85"
    }];

有没有办法可以检查localValues数组中是否已存在新的localProductCode

谢谢。

2 个答案:

答案 0 :(得分:5)

你可以尝试:

function isExisted(localValues, localProductCode) {
    for (var i = 0; i < localValues.length; ++i) {
        if (localValues[i].localProductCode == localProductCode) {
            return true;
        }
    }
    return false;
}

答案 1 :(得分:0)

这是一种查找巧合指数的方法(如 indexOf

Array.prototype.indexOfObj = function(key, value){
    for(var i = 0; i < this.length;) 
        if(this[i++][key] === value) return --i
    return -1
}

Items.localValues.indexOfObj("localValId", "NxtmZngRpGY56grkW"); //1
Items.localValues.indexOfObj("localValId", "WXLiCMJMixndtQtqZ"); //2

<强> Demo