JavaScriptFundamental (ES6), part 1
Object destructuring with renaming in JavaScript
20 Object destructuring and renaming
easyPull properties out of an object by name, rename two of them on the way out, ask for one that is not there, and pull an awkward key that is not a valid identifier.
Stuck? Three hints, smallest first
- 1. An object pattern matches by key, so the order you write the names in is irrelevant.
- 2.
{ from: to }renames: the key on the left, the new variable on the right. - 3. A key with a hyphen or a space has to be quoted, and then it must be renamed — there is no legal variable of that spelling.
const stall = { code: 'A1', owner: 'Ngozi', rentNgn: 12000 };
const { owner, code } = stall; // order does not matter
const { code: id, rentNgn: rent } = stall; // renamed on the way out
const { missing } = stall;
const { code: alias1, code: alias2 } = stall; // the same key twice
const { length } = 'Ikeja'; // a string is boxed first
const ledger = { 'rent-2024': 5000, 'due date': '2024-03-01' };
const { 'rent-2024': rent2024, 'due date': dueDate } = ledger;
console.log('by name :', owner, code);
console.log('renamed :', id, rent);
console.log('absent key :', missing);
console.log('twice :', alias1, alias2);
console.log('from a string :', length);
console.log('quoted keys :', rent2024, dueDate);
console.log('source intact :', stall);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('properties are matched by key, not by position', [owner, code], ['Ngozi', 'A1']);
test('a colon renames the binding', [id, rent], ['A1', 12000]);
test('a key that is not there gives undefined rather than an error', missing === undefined, true);
test('the same key may be taken twice under two names', [alias1, alias2], ['A1', 'A1']);
test('a primitive is boxed, so its properties destructure', length, 5);
test('an awkward key is quoted and renamed', [rent2024, dueDate], [5000, '2024-03-01']);
test('destructuring reads, so the source keeps every key', Object.keys(stall), ['code', 'owner', 'rentNgn']);
test('including the ones that were renamed', 'code' in stall, true);
Renaming reads backwards the first few times: { rentNgn: rent } takes the property rentNgn and calls it rent. The key is always on the left, the new name always on the right — the same order as in an object literal, which is what the pattern is mirroring.
Asking for a key that does not exist gives undefined instead of throwing, which is convenient and also why a typo in a pattern is silent. The one thing that does throw is the object itself being null or undefined; exercise 25 covers that.