jquery/javascript - overwriting values that exist
I have something similar to this:
...
meta: {
'orderby' : 'firstname',
'page' : 1,
'per' : 10
}
...
When I get send the request using ajax, part of my response contains some of this meta data. So I overwrite it with the new stuff. The server might send back something like:
meta: {
'page' : 1,
'per' : 10
}
The problem is that开发者_JS百科 it overwrites the orderby
key to be undefined
. I don't want to have the server send back everything, how can I leave a key's value if the key isn't sent back?
As you've said you're using jQuery, you can use its extend
function:
jQuery.extend(originalMeta, returnedMeta);
That will only overwrite properties in the target (originalMeta
, in the above) with properties from the source (returnedMeta
in the above) that actually exist. (No need to assign the result of the function to originalMeta
, it's modified in place.)
It's also dead easy without relying on jQuery:
var name;
for (name in returnedMeta) {
if (returnedMeta.hasOwnProperty(name)) {
originalMeta[name] = returnedMeta[name];
}
}
That uses a for..in
loop to loop through all (enumerable) properites on returnedMeta
, filters out any it inherits from its prototype (it probably doesn't inherit any, but...), and for ones that exist copies the values into originalMeta
.
You can use extend()
.
var meta = $.extend(meta, {
'page': 1,
'per': 10
});
T.J. Crowder notes that the first argument's object is modified, no need to return (though it will work as well).
The problem is that it overwrites the orderby key to be undefined
It doesn't overwrite the property, it overwrites the entire Object
. When you access an Object
's property that doesn't exist, you get undefined
.
精彩评论