首页 > 解决方案 > pythonic javascript中的嵌套默认字典

问题描述

我想在javascript中实现一个嵌套的默认字典,所以我可以去

nest['first']['second']['third'] = 'yay' 无需检查或初始化nest['first']&nest['first']['second']

在python中,这很容易

nested = defaultDict(lambda: deafultDict(dict()))

我尝试使用 Proxy 在 javascript 中实现相同的功能。结果并不像预期的那样,我无法弄清楚我错过了什么。从最后一条日志来看,看起来相同的默认字典正在作为参考传递。如何避免这种情况并使其按预期工作?

function defaultDict (defaultValue) {
  const handler = {
    get: (obj, prop) => {
      return prop in obj ? obj[prop] : defaultValue
    }
  }
  return new Proxy({}, handler)
}

var nested = defaultDict(defaultDict({}))

nested['first']['second']['third'] = 'yay'

console.log(nested['first']['second']['third']) // yay  OK
console.log(nested['first']['second']) // {third: 'yay'} OK

console.log(nested['first']) // result: {} expected {second: {third: 'yay'}}

console.log(nested['none']['gggggggggggg']) // result: {third: 'yay'} expected: {}

谢谢!

标签: javascript

解决方案


要实现任意深度的自动激活对象,您需要类似的东西

function defaultDict(defaultValueFn) {
  const handler = {
    get: (obj, prop) => {
      if(!(prop in obj)) obj[prop] = defaultValueFn();
      return obj[prop];
    },  
  };
  return new Proxy({}, handler);
}

var nestedDefaultDict = () => defaultDict(nestedDefaultDict);
var nested = nestedDefaultDict();

nested.a.b.c = 8;
nested.d.e.f = 8;
console.log(nested); // { a: { b: { c: 8 } }, d: { e: { f: 8 } } }

,就像在 Python 中一样defaultdict,你传入一个返回嵌套对象的可调用对象,而不是对象本身。


推荐阅读