customize the parameter of an object in react.js

I need a function to convert the list array into the filtered object, which works to react

const list = [{ id:1, name:"name1"}, { id:2, name:"name2"}]
filtered = {1:name1, 2:name2}

Answer

You can use reduce for that, try this:

const list = [{ id:1, name:"name1"}, { id:2, name:"name2"}]

const filtered = list.reduce((acc, {id, name}) => (acc[id] = name, acc), {});

console.log(filtered)

Leave a Reply

Your email address will not be published. Required fields are marked *