复制Javascript对象属性 [英] Copying Javascript object attributes

查看:63
本文介绍了复制Javascript对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 1 object coming from the server with multiple properties in which I want to hydrate it into a new object, changing the name of 1 property and keeping the rest.

代码:

JSON: {UserId:1,姓名:Woo,年龄:10}

我想要它的对象的格式:

The format of the object I want it in:

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;

我正在做的是基于这个回答,尝试将一些json解析为需要我更改1属性名称的格式。

What I'm doing is based on this answer, trying to parse some json into a format that requires me to change the name of 1 property.

推荐答案

对于这样一个简单的案例,你可以这样做:

For such a simple case, you could do something like:

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

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

For a more complex object with a large number of fields, you might prefer something like:

//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;

这篇关于复制Javascript对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆