最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript : check if JSON object exists in array - Stack Overflow

programmeradmin1浏览0评论

Thought it would be simple, but it isn't... I'm trying to check if, for example, this json object :

var strs = {
    strprop: "VALUE_A",
    strsub: "VALUE_B",
    subsub: "VALUE_C"
}

exists in an Array called regroup. This test doesn't work :

if(strs in regroup) {  //do stuff  }

Thanks

EDIT

regroup has this data:

[
    {
        "strprop": "répond ",
        "strsub": "au besoin suivant :",
        "subsub": "Economiser son carburant."
    },
    {
        "keyword": "coûte cher"
    },
    {
        "strprop": "répond ",
        "strsub": "au besoin suivant :",
        "subsub": "Economiser son carburant."
    },
    {
        "keyword": "carburant pollue"
    }
]

Thought it would be simple, but it isn't... I'm trying to check if, for example, this json object :

var strs = {
    strprop: "VALUE_A",
    strsub: "VALUE_B",
    subsub: "VALUE_C"
}

exists in an Array called regroup. This test doesn't work :

if(strs in regroup) {  //do stuff  }

Thanks

EDIT

regroup has this data:

[
    {
        "strprop": "répond ",
        "strsub": "au besoin suivant :",
        "subsub": "Economiser son carburant."
    },
    {
        "keyword": "coûte cher"
    },
    {
        "strprop": "répond ",
        "strsub": "au besoin suivant :",
        "subsub": "Economiser son carburant."
    },
    {
        "keyword": "carburant pollue"
    }
]
Share Improve this question edited May 6, 2014 at 9:50 Re Captcha 3,1332 gold badges25 silver badges34 bronze badges asked May 6, 2014 at 9:23 Spadon_Spadon_ 5052 gold badges5 silver badges11 bronze badges 2
  • it wouldn`t work. In regroup another objects? In javascript new Object != new Object – deadulya Commented May 6, 2014 at 9:26
  • 1 What is the content of regroup? When should the condition evaluate to true? – user77838 Commented May 6, 2014 at 9:27
Add a ment  | 

2 Answers 2

Reset to default 2

There is no generic methods available for paring object with another object in JS. Instead there is a way suggested in this @crazyx 's answer

JSON.stringify(obj1) === JSON.stringify(obj2) 

In your case,

for (var i=0; i<regroup.length; i++) { //iterate through each object in an array
     if (JSON.stringify(regroup[i]) === JSON.stringify(strs) ) {
             alert("EQUALS");
      }
}

JSFiddle

FYI: order of the key/value pair should be same else the above method will fail, example fiddle.

var strs={strprop: "VAL_A", strsub: "VAL_B", subsub: "VAL_C"}; var reg=[strs, 1, "2345"]; for(elmnt in reg){ if(reg[elmnt]==strs)
发布评论

评论列表(0)

  1. 暂无评论