繁体   English   中英

Javascript使用一些数组值动态初始化嵌套映射

[英]Javascript dynamically initialize nested map with some array values

我正在尝试根据用户输入动态生成以下格式的地图:

    {
      Jane: {
        Comments: ["Hello", "Hi"]
      },
      John: {
        Age: "999",
        Comments: "Hi"
      }
    }

键、值和嵌套都在运行时 - 所以最初我只知道顶级结构是一个映射。 我尝试使用以下代码在运行时进行此操作。

var nest = function(map, keys, v) {
    if (keys.length === 1) {
          map[keys[0]] = v;
    } else {
      var key = keys.shift();
      map[key] = nest(typeof map[key] === 'undefined' ? {} : map[key], keys, v);
    }

    return map;
};

var persons = new Map();
// Usage 
nest(persons, ['John', 'Comments'], 'Hi');
nest(persons, ['John', 'Age'], '999');

nest(persons, ['Jane', 'Comments'], 'Wow');
nest(persons, ['Jane', 'Comments'], 'Hello');

console.log(persons);

但是,它会覆盖Comments的值,而不是将其作为数组。 有人可以帮我创建这个带有数组值的非覆盖嵌套映射吗? (注意:除注释外的任何其他值都不是数组)

提前致谢。

您可以使用Array#reduce获取嵌套的Map ,然后您可以设置键。

 var nest = function(map, keys, v) { const lastKey = keys.pop(), innerMap = keys.reduce((acc, key)=>{ if(!acc.has(key)) acc.set(key, new Map); return map.get(key); }, map); if(lastKey !== 'Comments') innerMap.set(lastKey, v); else { if(!innerMap.has(lastKey)) innerMap.set(lastKey, []); innerMap.get(lastKey).push(v); } }; var persons = new Map(); // Usage nest(persons, ['John', 'Comments'], 'Hi'); nest(persons, ['John', 'Age'], '999'); nest(persons, ['Jane', 'Comments'], 'Wow'); nest(persons, ['Jane', 'Comments'], 'Hello'); console.log(persons); // Check browser console

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM