38
Destructuring Object with nested Array
2021-03-17 - JavaScript
1const myHero = {
2 name: 'Batman',
3 weapon: 'Batarang',
4 vehicles: [
5 { type: 'motorcycle', model: 'Batpod' },
6 { type: 'car', model: 'Batmobile' }
7 ]
8};
9
10let {name, vehicles: [{model: vehicle}]} = myHero;
11console.log(name, vehicle);
12// 'Batman', 'Batpod'
13
14let {name: newName, newVehicles = myHero.vehicles.map(v => ({model: v.model}))} = myHero;
15console.log(newName, newVehicles);
16// 'Batman', [ { model: 'Batpod' }, { model: 'Batmobile' }]
17
18let {name: anotherName, vehicles: anotherVehicles} = myHero;
19console.log(anotherName, anotherVehicles);
20// 'Batman', [ { type: 'motorcycle', model: 'Batpod' }, { type: 'car', model: 'Batmobile' }]
#JStipoftheday