首页 > 解决方案 > 如何将两个数组作为键和值合并到一个具有多个值的键的对象中?

问题描述

我的输入如下:

Input: keys = ['username', 'first-name', 'last-name', 'age', 'username'] and  values = ['johndoe', 'John', 'Doe', 35, 'johnny']

我希望我的输出看起来像这样:

Output: {username: ['johndoe', 'johnny'], firstName: 'John', lastName: 'Doe', age: 35}

到目前为止,这是我的代码,我知道这并不能完全解决用户名的'johndoe'问题'johnny'

function mergeArrays(keys, values) {
  var obj = {};
  if (keys.length != values.length)
    return null;
  for (var index in keys)
    obj[keys[index]] = values[index];
  return obj;
}

标签: javascriptarraysdictionaryobjectkey-value

解决方案


“forEach”函数可能很有用。

var keys = ['username', 'first-name', 'last-name', 'age', 'username'] 
var values = ['johndoe', 'John', 'Doe', 35, 'johnny']

var result = {}
keys.forEach(function(x, i) {
  if (result[x]) {
    if (typeof result[x] == 'Array') {result[x].push(values[i])} 
    else result[x] = [result[x],values[i]]
  }
  else result[x] = values[i]

})

console.log(result)


推荐阅读