javascript

JavaScript convert array to object

// convert array to object 

const users = [
    { id: 1, name: "Raj" },
    { id: 2, name: "Amit" }
];

/*
to : { '1': 'Raj', '2': 'Amit' }
to : 

	1 ## Raj
	2 ## Amit

*/

let userObject = users.reduce((result, each)=>{

	result[each.id] = each.name;
	return result;
	
}, {});

console.log( userObject );
// output : { '1': 'Raj', '2': 'Amit' }


for (let key in userObject) {     
    console.log(key , "##", userObject[key]); 
}

/* 
output 

1 ## Raj
2 ## Amit

*/