-1

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"
    }
]
Re Captcha
  • 3,125
  • 2
  • 22
  • 34
Spadon_
  • 495
  • 2
  • 5
  • 11

2 Answers2

2

There is no generic methods available for comparing 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.

Community
  • 1
  • 1
Praveen
  • 55,303
  • 33
  • 133
  • 164
  • @Spadon_: This isn't what you should do. It's unnecessarily expensive, and it could fail without warning. JSON serialization does not guarantee the order in which the object properties will be serialized. It's a bad idea to use constructs that make no guarantees. –  Oct 15 '14 at 18:41
1
var strs={strprop: "VAL_A", strsub: "VAL_B", subsub: "VAL_C"}; var reg=[strs, 1, "2345"]; for(elmnt in reg){ if(reg[elmnt]==strs)
saikiran.vsk
  • 1,788
  • 1
  • 10
  • 11