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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.