Javascript动态更改对象值

时间:2013-09-19 13:45:50

标签: javascript object

我有一个像这样的对象

var userobj = {
    user1: {
        firstName: 'abc',
        lastName: 'abc', 
        age: 29,
        address: {
            company: {
                location: 'xyz',
                city: 'xyz',
                street: 'xyz',
                city: 'xyz'
            },
            location: 'xyz',
            city: 'xyz',
            street: 'xyz',
            city: 'xyz'
        },
        payment: {
            visa: false,
            master: false,
            paypal: true
        },

    },

    user2: {
        firstName: 'abc',
        lastName: 'abc', 
        age: 29,
        address: {
            company: {
                location: 'xyz',
                city: 'xyz',
                street: 'xyz',
                city: 'xyz'
            },
            location: 'xyz',
            city: 'xyz',
            street: 'xyz',
            city: 'xyz'
        },
        payment: {
            visa: false,
            master: false,
            paypal: true
        }
    }
};

我想编写一个动态更改数据的函数,就像这个Funtkion

一样
function updateUserData(userName, key, value) {
    userobj[userName][key] = value;
}

仅在更改第一级键

时有效
updateUserData('user1', 'firstName', 'David');

有人可以告诉我如何更改功能,以便我可以将密钥更改为其他级别吗?也许用数组作为参数?喜欢这个

updateUserData('user1', ['address', 'company', 'location'], 'David');

3 个答案:

答案 0 :(得分:4)

function updateUserData(userName, keys, value) {
    var obj = userobj[userName];

    for(var i=0; i<keys.length-1; i++){
        obj = obj[keys[i]];
    }

    obj[keys[i]] = value;
}

http://jsfiddle.net/rPPK5/1/

答案 1 :(得分:1)

我知道设置嵌套属性的最简单方法是提供该属性的路径并附带新值。

一个简单的实现可能是:

function ObjectWrapper (obj) {
    this.object = obj;
    this.pattern = new RegExp(/^[[a-z\._]]+$/i);

    // set a property at the given path
    this.setPropertyValue = function (path, value) {
        if (this.pattern.test(path)) {
            eval('this.object.' + path + '=' + JSON.stringify(value));
        }else{
            throw new Error('Malformed property path');
        }
    }
}

用法:

var obj = {
    name: 'Bob',
    friends: {
        name: 'Joe'
    }
};

var wrapper = new ObjectWrapper(obj);
wrapper.setPropertyValue('friends.name', 'Rick');

答案 2 :(得分:0)

该实现的正则表达式是错误的,现在可以正常工作

function ObjectWrapper(obj) {
  this.object = obj;
  this.pattern = new RegExp(/^[[a-z\._]+$/i);

  // set a property at the given path
  this.setPropertyValue = (path, value) => {
    if (this.pattern.test(path)) {
      eval('this.object.' + path + '=' + JSON.stringify(value));
    } else {
      throw new Error('Malformed property path');
    }
  };
}

用法:

var obj = {
    name: 'Bob',
    friends: {
        name: 'Joe'
    }
};

var wrapper = new ObjectWrapper(obj);
wrapper.setPropertyValue('friends.name', 'Rick');