复制Javascript对象属性

问题描述 投票:10回答:6

我有一个来自服务器的对象具有多个属性,我希望将其水合成一个新对象,更改1属性的名称并保留其余属性。

码:

JSON:{ UserId: 1, Name: "Woo", Age: 10 }

我想要它的对象的格式:

var newObj = {}
newObj.id = jsonObj.UserId;
//Everything property below here is the same. How can i prevent writing this code?
newObj.Name = jsonObj.Name;
newObj.Age = jsonObj.Age;

我正在做的是基于这个answer,尝试将一些json解析成一种格式,要求我更改1属性的名称。

javascript
6个回答
16
投票

对于这样一个简单的案例,您可以执行以下操作:

var newObj = {id: jsonObj.UserId, Name: jsonObj.Name, Age: jsonObj.Age};

对于具有大量字段的更复杂对象,您可能更喜欢以下内容:

//helper function to clone a given object instance
function copyObject(obj) {
    var newObj = {};
    for (var key in obj) {
        //copy all the fields
        newObj[key] = obj[key];
    }

    return newObj;
}


//now manually make any desired modifications
var newObj = copyObject(jsonObj);
newObj.id = newObj.UserId;

4
投票

如果您只想复制特定字段

    /**
    * Returns a new object with only specified fields copied.
    * 
    * @param {Object} original object to copy fields from
    * @param {Array} list of fields names to copy in the new object
    * @return {Object} a new object with only specified fields copied
    */ 
    var copyObjectFields = function (originObject, fieldNamesArray)
    {
        var obj = {};

        if (fieldNamesArray === null)
            return obj;

        for (var i = 0; i < fieldNamesArray.length; i++) {
            obj[fieldNamesArray[i]] = originObject[fieldNamesArray[i]];
        }

        return obj;
    };


//example of method call
var newObj = copyObjectFields (originalObject, ['field1','field2']);

3
投票

我大多喜欢重复使用而不是重新创建所以我建议http://underscorejs.org/#clone


1
投票

不是真的理解你的问题,但这是我从现有对象中提取时通常做的事情:

var newObj = new Object(jsonObj);
alert(newObj.UserId === jsonObj.UserId); //returns true

那是你问的吗?希望有所帮助。


1
投票
function clone(o) {
 if(!o || 'object' !== typeof o)  {
   return o;
 }
 var c = 'function' === typeof o.pop ? [] : {};
 var p, v;
 for(p in o) {
 if(o.hasOwnProperty(p)) {
  v = o[p];
  if(v && 'object' === typeof v) {
    c[p] = clone(v);
  }
  else {
    c[p] = v;
  }
 }
}
 return c;
}

0
投票

Using Object.assign

var newObj = Object.assign({}, jsonObj);

reference (MDN)

Using JSON.parse and JSON.stringify;

var newObj = JSON.parse(JSON.stringify(jsonObj));
© www.soinside.com 2019 - 2024. All rights reserved.