'Adding array elements to object's key and values
If i have the following array
const Array = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress']
How could i make an object like
const Object = {
Michael: student,
John: cop,
Julia: actress,
}
Is there a way to make the even index elements to be the object's keys and the odd index elements to be the key's values?
Solution 1:[1]
A simple for loop that steps by two indexes at a time would work.
Try like below
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);
Solution 2:[2]
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);
Solution 3:[3]
You could split the array into chunks of size 2 and then convert it to an object with 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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amila Senadheera |
| Solution 2 | Salwa A. Soliman |
| Solution 3 | Unmitigated |
