如何克隆对象并将每个属性值设置为null?

时间:2015-01-29 12:02:12

标签: javascript object clone

根据标题,我需要在Javascript中克隆一个对象,如下所示,并将每个值设置为零。当然,对象属性可以改变。

  { _id: { action: null, date: null },
    avg: null,
    min: null,
    max: null,
    total: null }

1 个答案:

答案 0 :(得分:1)

// helper method to get the correct object type
function toType(x) {
  return ({}).toString.call(x).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}

// recursive function that sets all properties to null
// except objects which it passes back into the reset function
function reset(obj) {

  // clone the object
  var out = JSON.parse(JSON.stringify(obj));
  for (var p in out) {
    if (toType(out[p]) === 'object') {
      reset(out[p]);
    } else {
      out[p] = null;
    }
  }
  return out;
}

reset(obj);

DEMO