javascript - 如何自动将中间结构添加到嵌套对象(à la Python's defaultdict)?
问题描述
我想在创建嵌套对象时自动添加中间属性:
let a = {}
a.hello.world = 1
这会引发错误 ( Uncaught TypeError: Cannot set property 'world' of undefined
),因为hello
不存在。
在 Python 世界中,有一种特殊类型(JS 中dict
=的扩展Object
),其中中间结构是动态构建的:
>>> import collections
>>> a = collections.defaultdict(dict)
>>> a['hello']['world'] = 1
>>> a
defaultdict(<class 'dict'>, {'hello': {'world': 1}})
JavaScript中有这样的机制或类型吗?
解决方案
最快的方法似乎是明确声明
a.hello = {world:1}
它似乎比使用集合库的 python 更快......
_ 编辑 _
这是一个受此答案启发的解决方法
它远非干净(它创建复杂的对象并且肯定存在性能问题),但它允许 getter 链接
function dict () {
return new Proxy({}, {
get: function (target, name, receiver) {
if (!(name in target)) {
target[name] = dict(); // for it to work on multiple levels
};
return target[name];
}
});
};
var a = dict();
a.hello.yes.yes.yo = 5 ;
console.log(a.hello.yes.yes.yo); // 5
console.log(a); // Proxy {hello: Proxy}
将此视为一个开始而不是解决方案...
推荐阅读
- c++ - 2>链接:致命错误LNK1104:无法打开文件'dxerr.lib'
- java - 我的应用程序在单击按钮开始活动时崩溃,但在模拟器中工作
- java - 将 spring 1.2 升级到 spring 4.3.9 后事务回滚异常
- c# - Web API 默认可以同时处理多少个请求
- php - SQLSTATE[HY000] [2002] 连接尝试失败,因为连接方在一段时间后没有正确响应,
- python - 使用正则表达式获取具有特殊字符的字符串
- excel - Excel 公式 - 按员工编号排列日期
- sql - 在 SQL/Vb.net 中的多个表之间填充主键/外键
- php - Laravel 雄辩的多个查询
- docker - Dockerhub:列出给定图像的所有可用版本?