Деструктуризация обьектов

Как поменять в массиве с обьектами поле unread c false на true ?


Ответы (1 шт):

Автор решения: Aziz Umarov

Вариантов много, через map можно так думаю

let array = [{id:1, unread: false},{id:2, unread: false},{id:3, unread: true}]

console.log(array);

let array1 =array.map(item=> { item.unread = true; return item; });
 
console.log(array1);

можно через reduce

let array = [{id:1, unread: false},{id:2, unread: false},{id:3, unread: true}]

console.log(array);

let array1 =array.reduce((acc, item)=> { item.unread = true; acc.push(item); return acc; }, []);

console.log(array1);

или так как вы хотели

let array = [{id:1, unread: false},{id:2, unread: false},{id:3, unread: true}]

let array1 =array.map(item => ({...item, unread:true}));

console.log(array1);

По просьбе @UModeL добавил всякого мягкого для развития на скорую руку

let array = [{id:1, unread: false},{id:2, unread: false},{id:3, unread: true}]

let array1 =array.map(item => ({...item, unread: !item.unread}));

console.log(array1);

let array2 =array.map(item => ({...item, unread: { anyData: Math.random(), unread: item.id + ' ' + item.unread}}));

console.log(array2);

→ Ссылка