【问题标题】:How to split an array of strings & return a single object with key/value pairs如何拆分字符串数组并返回带有键/值对的单个对象
【发布时间】:2021-12-16 13:24:19
【问题描述】:

我有这个arraystrings

[ 
  'Back to Main Window: Retour à la fenêtre principale',
  'All Client Groups: Tous les groupes de clients',
  'Filter by Client: Filtrer par client' 
]

我想将其转换为 objectkey/value 对,如下所示:

{
   'Back to Main Window': 'Retour à la fenêtre principale',
   'All Client Groups': 'Tous les groupes de clients',
   'Filter by Client': 'Filtrer par client' 
}

我必须尝试使用​​map()split(),但我得到了这个输出:

const results = translations.map(translation => {
  const [key, value] = translation.split(':');

  return { key: value };
});

// results returns an "array" with the "key" word as key for all values :(
// [ { key: ' Retour à la fenêtre principale' },
//   { key: ' Tous les groupes de clients' },
//   { key: ' Filtrer par client' } ]
// 

【问题讨论】:

标签: javascript arrays object functional-programming


【解决方案1】:

map 覆盖数组,split 每一项通过': ',然后使用Object.fromEntries

const arr = [ 
  'Back to Main Window: Retour à la fenêtre principale',
  'All Client Groups: Tous les groupes de clients',
  'Filter by Client: Filtrer par client' 
]


const res = Object.fromEntries(arr.map(e => e.split(": ")))

console.log(res)

【讨论】:

    【解决方案2】:

    @Spectric 的替代解决方案是使用reduce,将您的数组转换为对象。

    const arr = [ 
      'Back to Main Window: Retour à la fenêtre principale',
      'All Client Groups: Tous les groupes de clients',
      'Filter by Client: Filtrer par client' 
    ];
    
    function transform(arr) {
      return arr.reduce((obj, line) => {
        const [key, value] = line.split(': ');
        obj[key] = value;
        return obj;
      }, {});
    }
    
    console.log(transform(arr));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      相关资源
      最近更新 更多