0

I'm trying to understand ES6, specifically destructuring feature.

How can I translate these lines using destructuring?

  const user = {...}
  const sessionData = ({
      session_id: user.session_id, 
      selector: user.selector, 
      validator: user.validator
  })

I tried

const sessionData = {session_id, selector, validator} = user

But it raises a syntax error, because of course destructuring is for giving a certain variable a value from an object but I don't understand how to do something like this with an object

zero298
  • 25,467
  • 10
  • 75
  • 100
steo
  • 4,586
  • 2
  • 33
  • 64
  • not quite sure what you're trying to do with `user`. To get the data into variables you'd simply use `let {session_id, selector, validator} = sessionData` – zfrisch Nov 26 '18 at 17:57
  • Are you trying to do this: https://stackoverflow.com/q/29620686/691711 ? – zero298 Nov 26 '18 at 17:57
  • You have to do it in two steps, destructure to just the props you need then rebuild the new object with shorthand. – jonrsharpe Nov 26 '18 at 17:58

3 Answers3

1

Use

const { session_id, selector, validator } = user;

Then

const sessionData = { session_id, selector,  validator };
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Nikko Khresna
  • 1,024
  • 8
  • 10
1

You could also do it like so (using anonymous functions)

const user = { session_id: 1, selector: "my-selector", validator: 1, unused: 3 };
const session = (({ session_id, selector, validator }) => ({ session_id, selector, validator }))(user);
console.log(session);
Jonathan Hamel
  • 1,393
  • 13
  • 18
  • 1
    This is also called an [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) – nook Aug 14 '19 at 15:06
0

You can use a function to create the new object with the fields you want.

const original = { a: 1, b: 2, c: 3 };

const pick = (o, fields) => fields.reduce((acc, key) => {

    acc[key] = o[key];

    return acc;
}, {});

console.log(pick(original, ['a', 'b']));

Or use the comma operator to destructure and assign.

const original = { a: 1, b: 2, c: 3 };

const newone = ({ a, b } = original, { a, b });

console.log(newone);

But keep in mind that the comma operator creates global variables, if the variables to assign the destructure are not declared. Hope this helps.

Alex G
  • 1,897
  • 2
  • 10
  • 15