当前位置: 动力学知识库 > 问答 > 编程问答 >

Javascript Dynamically Change Object Values

问题描述:

I have an object like this

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

}

}

};

I want to write a function to change the data dynamically like this Funtkion

function updateUserData(userName, key, value) {

userobj[userName][key] = value;

}

This works if only to change the first level key

updateUserData('user1', 'firstName', 'David');

can someone tell me how I can change the function so that I can change key into other levels too? Perhaps with an array as parameter? Like this

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

网友答案:
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/

网友答案:

The simplest way I know to set a nested property is by providing a path to that property accompanied with a new value.

A simple implementation could be:

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

Usage:

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

var wrapper = new ObjectWrapper(obj);
wrapper.setPropertyValue('friends.name', 'Rick');
分享给朋友:
您可能感兴趣的文章:
随机阅读: