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

jqueryjavascript - overwriting values that exist - Stack Overflow

programmeradmin3浏览0评论

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 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?

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 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?

Share Improve this question asked May 1, 2011 at 14:23 MatthewMatthew 15.7k28 gold badges91 silver badges124 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

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.

发布评论

评论列表(0)

  1. 暂无评论