首页 > 解决方案 > 如何自动将中间结构添加到嵌套对象(à 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中有这样的机制或类型吗?

标签: javascriptpythondictionary

解决方案


最快的方法似乎是明确声明

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}

将此视为一个开始而不是解决方案...


推荐阅读