3

I've got this:

const id = speakerRec.id;
const firstName = speakerRec.firstName;
const lastName = speakerRec.lastName;

and I think there is something like this but can't remember it.

const [id, firstName, lastName] = speakerRec;
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Pete
  • 3,111
  • 6
  • 20
  • 43
  • 6
    `{ }` not `[ ]` (in this case), [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) – Pointy Apr 08 '19 at 02:01
  • Possible duplicate of [What is destructuring assignment and its uses?](https://stackoverflow.com/questions/54605286/what-is-destructuring-assignment-and-its-uses) – Code Maniac Apr 08 '19 at 04:18

2 Answers2

7

You need to use {} for destructuring object properties:

const {id, firstName, lastName} = speakerRec;

[] is used for array destructuring:

const [one, two, three] = [1, 2, 3];

Demonstration:

const speakerRec = {
  id: "mySpeaker",
  firstName: "Jack",
  lastName: "Bashford"
};

const { id, firstName, lastName } = speakerRec;

console.log(id);
console.log(firstName);
console.log(lastName);

const [one, two, three] = [1, 2, 3];

console.log(one);
console.log(two);
console.log(three);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
6

It's an object, so use object destructuring (not array destructuring):

const { id, firstName, lastName } = speakerRec;
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320