javascript - 如何将两个数组作为键和值合并到一个具有多个值的键的对象中?
问题描述
我的输入如下:
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;
}
解决方案
“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)
推荐阅读
- python - python pip安装程序问题
- vba - 用于重新格式化部分标题的宏
- python-3.x - Django many to many 真的有必要吗?
- pdf - 如何在中使用 ReadAloud
- java - 尝试在 @Before 中实例化一个对象
- python - 如何在 sympy 中分解平方项
- google-app-engine - 数据存储模拟器消息类型不匹配
- php - 将 ü 转换为 \u00fc
- javascript - for...of、forawait...of 和 Promise.all 中的 Javascript async/await 执行顺序问题
- mulesoft - Mule 4.2.2 升级:错误 No value present MULE:SOURCE_RESPONSE_SENDorg.mule.extension.db.api.StatementResult