reduce array to object javascript
var arr = [{x:1},{x:2},{x:4}];
arr.reduce(function (a, b) {
return {x: a.x + b.x}; // returns object with property x
})
// ES6
arr.reduce((a, b) => ({x: a.x + b.x}));
// -> {x: 7}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]};
}, {});
arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])
var age = [ { Id: 16 }, { Id: 24 }, { Id: 32 } ];
var ageById = age.reduce((byId, age) => (byId[age.Id] = age, byId), {});
console.log(ageById);
would print out:
`{16:{Id: 16},24:{Id: 24},32:{Id: 32}}`