复制AJAX JSON对象到现有对象对象、AJAX、JSON

2023-09-10 13:50:15 作者:覀苝狼

我有几个Javascript的原型。最初,实例将具有唯一的ID的填充,与一些通用占位信息用于其他的数据。然后,我将消息发送到服务器的ID和对象类型(使用jQuery的AJAX功能),服务器返回一个JSON对象的所有缺少的信息(但无ID)。返回的对象中的变量有相同的名称与现有对象

I have several Javascript prototypes. Initially, instances will have only ID's filled in, with some generic place holder information for other data. I then send a message to the server with the ID and the object type (using jQuery's AJAX function) and the server returns a JSON object with all the missing information (but no ID). The variables in the returned object have the exact same name as those in the existing object.

什么是转让本到现有的空对象最简单的方法?我已经想出了一些替代品

What's the easiest way to transfer this into the existing empty object? I've come up with a few alternatives

设置对象相等返回的对象,然后复制ID(失去原型的功能呢?) 创建一个函数为每个对象,它接受一个对象具有相同的结构,并将数据复制 通过键值对的JSON对象的循环,并将其复制到现有的对象

如果我用的是第三种选择,这是做了正确的方法是什么?

If I use the third option, is this the correct way to do that? :

for (var key in json) {
    if (object.hasOwnProperty(key)) {
        object[key] = json[key];
    }
}

假设 JSON 在返回对象和对象是现有的对象。

assuming json is the returned object and object is the existing object.

推荐答案

试试这个使用 延长() :

Try this using extend():

var newObject = jQuery.extend({}, oldObject);