创建"shortcut"以操作深度嵌套的对象键



我有一个嵌套很深的对象,在我的代码中,我经常需要像这样操作数据:

var current_index = test_dict['current']['index']
var current_section = test_dict['current']['section']
test_dict[current_section]['data']['words'][current_index]

所以你可以看到,当访问对象时,我使用了引用对象其他部分的变量。这对我来说工作得很好,但在我的代码中,我还需要定期更新current_index和current_section。

由于这些变量只是浅层复制/引用,而不是直接快捷键到那些实际值,执行current_index++会增加current_index,但不会增加test_dict['current']['index']

在我的代码中,test_dict需要存储所有当前信息,所以我试图找出如何在不输入深度嵌套路径的情况下直接更新该字典。

我知道我可以使用点表示法,但这不会节省我任何时间,因为我必须这样做:

test_dict[test_dict.current.section]['data']['words'][test_dict.current.index]

我知道我也可以在函数的开头创建一个let current_index和let current_section的引用,但是由于我必须在几乎每个函数中操作那个test_dict对象,因此定义它数百次是不切实际的。

有更好的方法吗?我应该只是创建一个getCurrentIndex()函数,然后这样做吗?

test_dict[getCurrentSection()]['data']['words'][getCurrentIndex()]

由于这些变量只是浅拷贝/引用,而不是直接快捷键到那些实际值,执行current_index++会增加current_index,但不会增加test_dict['current']['index']

好吧. .对象(和数组)是指针/引用。数字、字符串、布尔值等都是副本。如果你想要东西的快捷方式,这里有一个例子

var current=test_dict['current'];
var current_index = current['index'];
var current_section = current['section'];
test_dict[current_section]['data']['words'][current_index];
current['index']++ //index inside test_dict would get added to

也许你可以试试Proxy object:

const dict = {
current: {
index: 1,
section: "test1"
},
test1: {
data: {
words: ["test1 index0", "test1 index1", "test1 index2"]
}
},
test2: {
data: {
words: ["test2 index0", "test2 index1", "test2 index2"],
other: {
sub1: {
sub1_1: ["some", "text", "blah"],
sub1_2: "single string",
sub1_3: {}
}
}
},
blah: {
sub1: {
sub1_4: 123456
}
}
}
}
const test_dict = new Proxy(dict, {
get: function (target, key, receiver)
{
const data = target[dict.current.section] && target[dict.current.section][key] || target[key];
if (typeof data === 'object' && data !== null && !(data instanceof Array))
return new Proxy(data, this)
return data instanceof Array && data[dict.current.index] || data || target;
}
});
console.log("[data][words]", test_dict['data']['words']);
test_dict.current.index = 2
console.log("[data][words]", test_dict['data']['words']);
test_dict.current.section = "test2"
test_dict.current.index = 0
console.log("[data][words]", test_dict['data']['words']);
console.log("data.words", test_dict.data.words);
console.log("data", test_dict.data);
console.log("sub1", test_dict['data']['other']['sub1']);
console.log("sub1_1", test_dict['data']['other']['sub1']['sub1_1']);
console.log("sub1_2", test_dict['data']['other']['sub1']['sub1_2']);
console.log("sub1_3", test_dict['data']['other']['sub1']['sub1_3']);
console.log("blah.sub1_4", test_dict['blah']['sub1']['sub1_4']);

最新更新