如果我有以下数组
const Array = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress']
我怎么能做一个像这样的物体
const Object = {
Michael: student,
John: cop,
Julia: actress,
}
有没有办法让偶数索引元素成为对象的键,奇数索引元素成为键的值?
一次遍历两个索引的简单for循环就可以了。
尝试低于
const array = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress'];
const output = {}
for(let i = 0; i < array.length; i+=2){
output[array[i]] = array[i+1]
}
console.log(output);
let arr = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress'];
let obj={};
arr.forEach((element, index) => {
if(index % 2 === 0){
obj[element] = arr[index+1];
}
})
console.log(obj);
您可以将数组拆分为大小为2的块,然后将其转换为具有Object.fromEntries
的对象。
let arr = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress'];
let obj = Object.fromEntries([...Array(arr.length / 2)]
.map((_, i)=>arr.slice(i * 2, i * 2 + 2)));
console.log(obj);