Javascript 从字符串数组生成映射

Javascript 从字符串数组生成映射,javascript,string,Javascript,String,我正试图根据一些预定义的逻辑在映射中存储一些服务器名称 例如,如果名称为: "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" ] } 两个“-”之间的第一个字母始终是关键 我对javas

我正试图根据一些预定义的逻辑在映射中存储一些服务器名称

例如,如果名称为:

"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];
  }
}
试试这个:

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”

您可以使用
reduce()

let server=[“temp-a-name1”、“temp-a-name2”、“temp-b-name1”、“temp-b-name2”];
让map=servers.reduce((acc,server)=>{
让key=server.charAt(server.indexOf(“-”)+1);
if(附件[键])
acc[key].推送(服务器);
其他的
acc[密钥]=[服务器];
返回acc;
}, {})

console.log(map)
我会使用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];
常量namesWithKey=map[key]| |[];
返回{…map[key]:[…namesWithKey,name]};
}, {});
控制台日志(map)您还可以使用新的数据结构,如下所示:

const servers=[“temp-a-name1”、“temp-a-name2”、“temp-b-name1”、“temp-b-name2”];
常量映射=新映射();
servers.forEach(项=>{
const key=item.split('-')[1];
const value=map.get(key)| |[];
价值推送(项目);
map.set(键、值);
});
//控制台日志
for(map.entries()的var[key,value]{
console.log(key+'='+值);

}
坚持使用您的版本。IMO代码可读且易于理解,因此无需重构。顺便说一句,这样的问题更适合你。
reduce()
不是ES6的特性