【问题标题】:Generate map from string array从字符串数组生成地图
【发布时间】:2019-09-14 07:38:55
【问题描述】:

我正在尝试根据一些预定义的逻辑将一些服务器名称存储在地图中。

例如,如果名称是:

"temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"

它们将存储在地图中:

{
  a: [
    "temp-a-name1",
    "temp-a-name2"
  ],
  b: [
    "temp-b-name1",
    "temp-b-name2"
  ]
}

两个“-”之间的第一个字母永远是键

我对 javascript 不太熟悉,所以我以天真的方式做到了这一点,但我想知道是否有更好、更 JavaScript 的方式来做到这一点。

const servers = ["temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"];

let map = {};
let key;
for (const server of servers) {
  key = server.charAt(server.indexOf("-") + 1);
  if (key in map) {
    map[key].push(server);
  } else {
    map[key] = [server];
  }
}

【问题讨论】:

标签: javascript string


【解决方案1】:

您可以使用reduce() function:

let servers = ["temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"];

let map = servers.reduce((acc, server) => {
  let key = server.charAt(server.indexOf("-") + 1);

  if (acc[key])
    acc[key].push(server);
  else
    acc[key] = [server];
    
  return acc;
}, {})

console.log(map)

【讨论】:

  • reduce() 不是 ES6 特性
【解决方案2】:

试试这个:

const servers = ["temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"];
const result = servers.reduce((acc, cur) => ({
    ...acc,
  [cur.split('-')[1]]: (acc[cur.split('-')[1]] || []).concat([cur]),
}), {})
console.log(result);

我认为这算是“javascripty”

【讨论】:

    【解决方案3】:

    我会使用reduce。获取密钥的简单方法可能是.split('-')[1]

    const names = ['temp-a-name1', 'temp-a-name2', 'temp-b-name1', 'temp-b-name2'];
    const map = names.reduce((map, name) => {
      const key = name.split('-')[1];
      const namesWithKey = map[key] || [];
    
      return { ...map, [key]: [...namesWithKey, name] };
    }, {});
    
    console.log(map);

    【讨论】:

      【解决方案4】:

      您还可以使用新的Map 数据结构,如下所示:

      const servers = ["temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"];
      
      const map = new Map();
      
      servers.forEach(item => {
        const key = item.split('-')[1];
        const value = map.get(key) || [];
        value.push(item);
        
        map.set(key, value);
      });
      
      // CONSOLE LOG
      for (var [key, value] of map.entries()) {
        console.log(key + ' = ' + value);
      }

      【讨论】:

        猜你喜欢
        • 2012-08-16
        • 2018-07-26
        • 2016-05-06
        • 1970-01-01
        • 1970-01-01
        • 2011-12-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多