1

Suppose I had an object called Student

const student = {
  id: 4625230,
  name: 'Sam',
  dob: '01/01/2000',
  sex: 'M',
  graduated: false
}

I would like to destructure it in such a way to pick certain fields (name, dob, sex) and assign it to object A, while destructuring all remaining fields into object B

const A = {
  name: 'Sam',
  dob: '01/01/2000',
  sex: 'M'
}
const B = {
  id: 4625230,
  graduated: false
}

Is there any syntax for this? I'm thinking of something like:

const {A={name, dob, sex}, ...B} = student

aelesia
  • 184
  • 7

1 Answers1

1
const {name, dob, sex, ...b} = student;
const a = { name, dob, sex}
  • Is it possible to do it with a 1 liner without having to type `name, dob, sex` twice? – aelesia May 06 '21 at 14:01
  • I don't think so – Yassine Ben Amar May 06 '21 at 14:13
  • @aelesia You can do it using lodash `pick`. I am surely not recommending to import a library just to get a subset of keys. Alternatively, you can also implement pick yourself if you want. [Here is an example.](https://stackoverflow.com/a/56592365) You will need to do something like this then: ```const a = pick(student, 'name', 'dob', 'sex'); const b = pick(student, 'id', 'graduated');``` If you want one-liner then `const [a,b] = [pick(...), pick(...)];` ;P But if using this you need to know names of _all remaining fields_. – brc-dd May 06 '21 at 16:28