There are multiple ways to convert an array to object.
Using Array.reduce() Method:
Code:
var str = ["a", "b", "c", "d"]
var res = str.reduce((acc, current,index) => {
return {...acc,[index]:current}
},{})
console.log(res)
Output
{ '0': 'a', '1': 'b', '2': 'c', '3': 'd' }
Other ways are more simple.
Way 1 using spread operator:
Code:
let names =["sagar","sangram","sachin"]
let objNameSpread = {...names}
console.log(objNameSpread)
Output:
{ '0': 'sagar', '1': 'sangram', '2': 'sachin' }
Way2 using Object.assign:
Code:
let objNameAssign =Object.assign({}, names);
console.log(objNameAssign)
Output:
{ '0': 'sagar', '1': 'sangram', '2': 'sachin' }
No comments:
Post a Comment