convert array into object using reduce javascript code example
Example 1: javascript Convert an array of objects to a single object
const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});
toObject(
[
{ id: '1', name: 'June', gender: 'Female' },
{ id: '2', name: 'Alex', gender: 'Male' },
{ id: '3', name: 'Harry', gender: 'Male' },
],
'id'
);
Example 2: reduce array to object javascript
const posts = [
{id: 1, category: "frontend", title: "All About That Sass"},
{id: 2, category: "backend", title: "Beam me up, Scotty: Apache Beam tips"},
{id: 3, category: "frontend", title: "Sanitizing HTML: Going antibactirial on XSS attacks"}
];
const categoryPosts = posts.reduce((acc, post) => {
let {id, category} = post;
return {...acc, [category]: [...(acc[category] || []), id]};
}, {});