2

I'm creating a feature that provides a get() and set() function to read and update values from a JavaScript object. The trick is that I'm using a dot notated string to specify the properties.

I've got the get() working fine, it's the set() that I'm having troubles with.

Sample data:

var data = {
    person: {
        name: 'Fred',
        birthday: '19840101',
        address: {
            street: '123 Main St.',
            city: 'Anytown',
            state: 'NY',
            zip: '123123'
        },
        family: {
            spouse: 'Sally',
            children: ['Sam', 'Frank', 'Susan']
        }
    }
};

get() function:

function get (path) {
    var parts = path.split('.'),
        tmp = data;
    for (var i = 0, l = parts.length; i < l; ++i) {
        if (tmp[parts[i]]) {
            tmp = tmp[parts[i]];
        }
        else {
            tmp = null
            break;
        }
    }
    return tmp;
}

console.log(get('person.name')); // Fred
console.log(get('person.family.children')); // ['Sam', 'Frank', 'Susan']
console.log(get('person.jobs.apple')); // null

set() function:

var foo = null;
function set (path, val) {
    var parts = path.split('.')
        tmp = {},
        foo = data;

    for (var i = 0, l = parts.length; i < l; ++i) {
        if (tmp[parts[i]]) {
            tmp = data[parts[i]];
        }
        else {
            tmp = {};
        }
        if (i+1 === l) {
            tmp = val;
        }
        data[parts[i]] = tmp;
    }
}

set('person.name', 'Dave'); // replace existing name
set('person.family.children', ['Tim', 'Matt', 'Kathy']); // replace existing array
set('person.jobs.apple', 'developer'); // should create the necessary properties
console.log(data);

I end up with the following object:

obj = {
    person: {},
    name: "Dave",
    family: {},
    children: ["Tim","Matt","Kathy"],
    jobs: {},
    apple: "developer"
}

Any thoughts on how to accomplish this?

4

3 回答 3

2

为此,您根本不需要任何功能。

看到这个

var data = {
    person: {
        name: 'Fred',
        birthday: '19840101',
        address: {
            street: '123 Main St.',
            city: 'Anytown',
            state: 'NY',
            zip: '123123'
        },
        family: {
            spouse: 'Sally',
            children: ['Sam', 'Frank', 'Susan']
        }
    }
};

alert(data.person.name);
data['person']['name'] = 'Tim';
alert(data['person']['name']);

还有这个答案可能会有所帮助

Javascript 对象键值编码。动态设置嵌套值

于 2011-11-18T06:11:30.400 回答
0

set您的代码中似乎有一些拼写错误。

该行tmp = data[parts[i]];真的应该是tmp = tmp[parts[i]];。然后您可能希望将其放入一个新变量中 - 比如说 , newTmp- 以便您可以稍后将其分配回对象:

    tmp[parts[i]] = newTmp; 
    tmp = newTmp;
于 2011-11-18T06:03:53.530 回答
0

您的问题似乎是 data[parts[i]] = tmp; 在 set 函数的末尾。

于 2011-11-18T06:07:09.287 回答