2

我有一个像这样的对象

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');
4

3 回答 3

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

于 2013-09-19T13:50:20.103 回答
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');
于 2013-09-19T13:58:45.190 回答
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');
于 2020-06-04T16:53:02.710 回答