繁体   English   中英

如何分配字符串数组的键/值对

[英]How do i assign key / value pairs of an array of strings

let arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue']

我想为上面数组中的字符串分配键值对

例如:

[{drink: 'soda'},
 {name: 'john'},
 {someKey:'someValue'}
]

我花了几个小时试图解决这个问题......我试过用 map 方法接近它,但我对 javascript 的有限知识一直在返回错误......

如果有人可以帮助我,我将不胜感激。 谢谢

一个简单的老式循环,每次迭代将步长增加 2。

注意:这将为您提供一个具有键/值对的对象,这使得(在我看来)比每个具有一个键/值对的对象数组更有用的数据结构。 如果您正在寻找一组对象@sonEtLumiere 的答案是正确的。

 const arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue']; // Initialise empty object const out = {}; // Loop over the array in steps of 2 so // that we can access `i` (the key) and // `i + 1` (the value) on each iteration for (let i = 0; i < arr.length; i += 2) { out[arr[i]] = arr[i + 1]; } console.log(out); console.log(out.drink); console.log(out.name); console.log(out.someKey);

你可以用一个简单的 for 循环来做到这一点:

 let arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue']; let result = []; for(let i = 0; i < arr.length; i+=2) { let obj = {} obj[arr[i]] = arr[i+1]; result.push(obj) } console.log(result)

那将是最简单的方法:

 const arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue'] const obj = {} for (let i = 0; i < arr.length; i += 2) { obj[arr[i]] = arr[i + 1] } console.log(obj)

或者如果你真的想要一个单线器

 const arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue'] const result = arr.reduce((fin, str, i, arr) => i & 1 ? fin : { ...fin, [str]: arr[i + 1] }, {}) console.log(result)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM