3

i have 2 objects, which are associated arrays from PHP in JSON. They have an structure like that´:

[object]
    ["green"]
         ['value1']=integer
         ['value1']=array...
    ["blue"]
         ['value1']=integer
         ['value1']=array...
    [...]

The 1st Version of this object is loaded from webserver periodically using JSON. By receiving this new JSON string from webserver, the current object moved to the variable "oldObj" while the new data stored into the variable "newObj". It could be possible, that the new object will have less elements than the old object, like this:

[newObj]
    ["green"]
         ['value1']=integer
         ['value1']=array...

As you can see: "blue" is missing.

Now i need this elements which are part of the old Object / that means: which are missing at the new object (at this example: element "blue")

I tried the following, but without any success:

[...]
    var newObj=data;
    $.each (oldObj,function(i,n)
            {if (newObj.i.length<1) {alert('missing: '+i);}
            }
         );//end foreach

Error message: "newObj.i is undefined"

The Bndr
  • 13,204
  • 16
  • 68
  • 107
  • Should be `newObj[i]` but that won't help you either. Objects don't have a "length" like arrays do. – Felix Kling Jun 21 '11 at 14:53
  • 1
    possible duplicate of [Doing a "Diff" on an Associative Array in javascript / jQuery?](http://stackoverflow.com/questions/2558800/doing-a-diff-on-an-associative-array-in-javascript-jquery) – Felix Kling Jun 21 '11 at 14:55
  • 1
    This might help.. http://stackoverflow.com/questions/1200562/difference-in-json-objects-using-javascript-jquery – Neeraj Jun 21 '11 at 14:56
  • @Felix Kling i searched trough SO for an answer, but i didn't found your link. Thank you - i will check it. – The Bndr Jun 21 '11 at 14:59
  • @Felix Kling @Neeraj +1 - those links helps me a lot to find an solution --- in combination with the answer from wong2. Thanks at all! – The Bndr Jun 21 '11 at 15:20

1 Answers1

1

According to your description, I think newObj or oldObj can be wrote as:

var newObj = {
    "green": [
        integer,
        [array]
    ],
    "blue": [
        integer,
        [array]
    ]
};    

Is it right?

You could use :

for(p in Obj){
    if(Obj.hasOwnProperty(p)){
        // do something with p
    }
}  

to loop through the Obj's properties.

Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
wong2
  • 34,358
  • 48
  • 134
  • 179
  • shouldn't it be for(p in oldObj){ if(newObj.hasOwnPropery(p)){ // do something with p } ....? } – The Bndr Jun 21 '11 at 15:09
  • @Bndr of course you could do that, I'm just suggesting the general way to loop an object's properties. – wong2 Jun 21 '11 at 15:13