【问题标题】:how to make an array of strings into a key value pair object, making the value an array?如何将字符串数组变成键值对对象,使值成为数组?
【发布时间】:2021-04-13 00:03:50
【问题描述】:

我有一个这样的字符串数组:

[
    "hl7_file_type_1.msgtype",
    "hl7_file_type_1.filename",
    "hl7_file_type_2.msgtype",
    "hl7_file_type_2.filename",
    "hl7_file_type_3.msgtype",
    "hl7_file_type_3.filename"
]

我正在尝试将其转换为键值对对象,如下所示 (expected result):

{
"hl7_file_type_1": ["msgtype","filename"],
"hl7_file_type_2": ["msgtype","filename"],
"hl7_file_type_3": ["msgtype","filename"],
}

这是我的尝试方式:

let tmp = {};
for (let i = 0; i < this.regexArray.length; i++){
      let split = this.regexArray[i].split('.');
      tmp[split[0].trim()] = split[1].trim();
    }
    console.log('Key Value')
    console.log(tmp);

这是返回的内容:

{
    "hl7_file_type_1": "filename",
    "hl7_file_type_2": "filename",
    "hl7_file_type_3": "filename"
}

我怎样才能改变我的函数来返回上面提到的expected result

【问题讨论】:

  • 嗨!请使用tour(您将获得徽章!)并通读help center,尤其是How do I ask a good question? 您最好的选择是进行研究,search 以获取有关 SO 的相关主题,然后试一试. 如果您在进行更多研究和搜索后遇到困难并且无法摆脱困境,请发布您的尝试minimal reproducible example,并具体说明您遇到的问题。人们会很乐意提供帮助。
  • 这真的是 TypeScript 吗?此处的示例代码可能会使用tmp[split[0].trim()] 给出编译器警告,因为tmp 被推断为类型{}。如果这与 TypeScript 无关,也许应该删除标签?

标签: javascript typescript key-value


【解决方案1】:

您可以使用reduce轻松实现此目的

const arr = [
  "hl7_file_type_1.msgtype",
  "hl7_file_type_1.filename",
  "hl7_file_type_2.msgtype",
  "hl7_file_type_2.filename",
  "hl7_file_type_3.msgtype",
  "hl7_file_type_3.filename",
];

const result = arr.reduce((acc, curr) => {
  const [prop, type] = curr.split(".");
  if (!acc[prop]) acc[prop] = [type];
  else acc[prop].push(type);

  return acc;
}, {});

console.log(result);

【讨论】:

    【解决方案2】:

    应该做一点映射和归约

    const input = [
        "hl7_file_type_1.msgtype",
        "hl7_file_type_1.filename",
        "hl7_file_type_2.msgtype",
        "hl7_file_type_2.filename",
        "hl7_file_type_3.msgtype",
        "hl7_file_type_3.filename"
    ]
    
    const result = input.map(i => i.split(".")).reduce( (acc,[key,value]) => {
      return {
        ...acc,
        [key]: [...(acc[key] || []), value]
      }
    },{});
    
    console.log(result);

    【讨论】:

    • 一次又一次地创建新的数组和对象,性能够不够?
    • @SomShekharMukherjee 可能 - 对于 6 个项目的数组(甚至 600 个!)更大的数字,不是那么多!
    【解决方案3】:

    只需map 然后reduce

    const data = [
      "hl7_file_type_1.msgtype",
      "hl7_file_type_1.filename",
      "hl7_file_type_2.msgtype",
      "hl7_file_type_2.filename",
      "hl7_file_type_3.msgtype",
      "hl7_file_type_3.filename",
    ];
    
    const res = data
      .map((d) => d.split("."))
      .reduce((r, [k, v]) => ((r[k] ??= []), r[k].push(v), r), {});
    
    console.log(res);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 2019-01-14
      • 2020-01-28
      相关资源
      最近更新 更多