I have an array const arr = ['boy', '2', 'girl', '25', 'dog', '6']
and I want to convert it to and object so it will be come newCreatedObject = {'boy': '2', 'girl': '25', 'dog': '6'}
.
Here is what i have tried:
const newCreatedObject = arr.reduce((acc, cur, i, arr) => {
return {...acc, [cur]: arr[i + 1]};
}, {})
This is what I get {'6': undefined, '25': 'dog', '2': 'girl', 'boy': '2', 'girl': '25', 'dog': '6'}
the result I want is coming at the later of the object
You need to take only each second element for the result.
const
array = ['boy', '2', 'girl', '25', 'dog', '6'],
object = array.reduce(
(acc, cur, i, arr) => i % 2
? { ...acc, [arr[i - 1]]: cur }
: acc,
{}
);
console.log(object);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments