如何创建对象的空副本?

时间:2014-07-09 20:43:19

标签: javascript

我正在从JSON创建一些对象,我想制作一个对象的空副本。我会拥有所有相同的属性,但空值。有什么好方法可以做到这一点?

现在我正在按照以下方式进行操作,但希望它是我从我收到的JSON创建的对象中动态的。

var myObject = { "Address": { "Address1": "", "Address2": "", "Address3": "", "Address4": "", "City": "", "": "", "": "", "Country": "", "Id": -1, "LastModified": "", "PostBackAction": null }, "Id": -1, "Amenities": "", "Directions": "", "LastModified": "", "LocalAttractions": "", "LocalLodging": "", "LocalRestaraunts": "", "Name": "", "Pictures": "", "Prices": "", "Region": 0, "PostBackAction": null };

一种可行的解决方案,因为它复制了值而无法正常工作。

var myObject = JSON.parse(JSON.stringify(objectToBeCopied));

3 个答案:

答案 0 :(得分:3)

您可以使用创建对象结构副本的函数,并为每种数据类型使用默认值:

function skeleton(source, isArray) {
  var o = Array.isArray(source) ? [] : {};
  for (var key in source) {
    if (source.hasOwnProperty(key)) {
      var t = typeof source[key];
      o[key] = t == 'object' ? skeleton(source[key]) : { string: '', number: 0, boolean: false }[t];
    }
  }
  return o;
}

演示:http://jsfiddle.net/Guffa/ym6ZJ/

答案 1 :(得分:2)

var getCopy = function(objectToCopy){     
    var copy = {};

    for(var prop in myObject){
       if(typeof(objectToCopy[prop])==="object"){
           copy[prop]= getCopy(objectToCopy[prop]);
       }
       else{
            copy[prop]=null;
       }
    }

    return copy;
}

答案 2 :(得分:0)

希望这就是你要找的东西:

    var myObject = function(){
    this.address = {
        'Address1': '',
        'Address2': '',
        'Address3': '',
        'Address4': '',
        'City': '',
        'Country': '',
        'Id': 0,
        'LastModified': '',
        'PostBackAction': null
    };
    this.Id = -1;
    this.Amenities = '';
    this.Directions = '';
    this.LastModified = '';
    this.LocalAttractions = '';
    this.LocalLodging = '';
    this.LocalRestaraunts = '';
    this.Name = '';
    this.Pictures = '';
    this.Prices = '';
    this.Region = 0;
    this.PostBackAction = null;

}       
// create two new objects
var objectOne = new myObject();
var objectTwo = new myObject();

console.log(objectOne);

//modify the first
objectOne.address.Address1 = 'Lol Street';
console.log(objectOne);
//notice the second one was not changed
console.log(objectTwo);