jQuery 将 AJAX JSON 对象复制到现有对象中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16373422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:01:50  来源:igfitidea点击:

Copying AJAX JSON object into existing Object

javascriptjqueryajaxjson

提问by Jaws212

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.

我有几个 Javascript 原型。最初,实例将只填充 ID,其他数据的一些通用占位符信息。然后我用 ID 和对象类型(使用 jQuery 的 AJAX 函数)向服务器发送一条消息,服务器返回一个包含所有缺失信息(但没有 ID)的 JSON 对象。返回对象中的变量与现有对象中的变量具有完全相同的名称。

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

将其转移到现有的空对象中的最简单方法是什么?我想出了几个替代方案

  • set the object equal to the returned object, then copy in the id (loses prototype functions?)
  • create a function for each object that takes an object with identical structure and copies the data
  • loop through the key-value pairs of the JSON object to and copy them to existing object
  • 将对象设置为等于返回的对象,然后复制 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];
    }
}

assuming jsonis the returned object and objectis the existing object.

假设json是返回的对象并且object是现有的对象。

采纳答案by pala?н

Try this using extend():

试试这个使用extend()

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

回答by Karthik Sankar

Alternative without jQuery is to use the javascript Object.assign method.

不使用 jQuery 的替代方法是使用 javascript Object.assign 方法。

Object.assign(targetObject, json);

Object.assign(targetObject, json);

回答by HMR

You can use jQuery.extend: http://api.jquery.com/jQuery.extend/

您可以使用 jQuery.extend:http: //api.jquery.com/jQuery.extend/

$.extend(object1,object2);

If your JSON is a string then create an object from that first:

如果你的 JSON 是一个字符串,那么首先从它创建一个对象:

var object1=$.parseJSON(myJsonString);