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"

5
  • Should be newObj[i] but that won't help you either. Objects don't have a "length" like arrays do. Commented Jun 21, 2011 at 14:53
  • 1
    possible duplicate of Doing a "Diff" on an Associative Array in javascript / jQuery? Commented Jun 21, 2011 at 14:55
  • 1
    This might help.. stackoverflow.com/questions/1200562/… Commented Jun 21, 2011 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. Commented Jun 21, 2011 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! Commented Jun 21, 2011 at 15:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

shouldn't it be for(p in oldObj){ if(newObj.hasOwnPropery(p)){ // do something with p } ....? }
@Bndr of course you could do that, I'm just suggesting the general way to loop an object's properties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.