简体   繁体   中英

How to use a destructuring assignment inside an object

Is it possible to use a destructuring assignment inside an object?

This works

        const test = {a: 'hey', b: 'hello'}
        const {a,b} = test;
        const destruct = {
            a,
            b
        };

Would like to do this

    const test = {a: 'hey', b: 'hello'}
    // something like this
    const destruct = {
        {a,b}: test
    };

    const destruct = {
        {a}: test,
        {b}: test
    };

If I understand correctly, it seems the spread syntax is a good fit for what you need.

The spread syntax " ... " allows you to "spread" the key/value pairs from a source object (ie test ) to a target object (ie destruct ):

 const test = { a: 'hey', b: 'hello', c: 'goodbye' } const destruct = { // {a,b}: test <-- invalid syntax ...test // equivalent using the "spread" syntax }; console.log(destruct) 

Additionally, if you wanted to select a subset of keys from a source object and spread those into a target object then this can be achieved by the following:

 const test = { a: 'hey', b: 'hello', c: 'goodbye' } /* Spread subset of keys from source object to target object */ const welcomeOnly = { ...({ a, b } = test, { a, b }) } console.log('exclude goodbye, show welcomes only:', welcomeOnly); 

The second example works by destructing the source object (ie test ) into an object, with the subset of keys that we want ( a and b ).

In the scope of that expression (ie everything between the ( and ) ), these keys are accessible as local variables. We take advantage of this, and pass those to a new object (ie { a, b } ). Because the new object is declared after the , , it is returned as the result of the expression.

If you are trying to take a subset of properties you can use the rest operator

 const test = { a: 'hey', b: 'hello', c: 'goodbye' }; const { c, ...destruct } = test; console.log(destruct); 

This assigns c to a const and the the left over properties are assigned to the const destruct. List all the unwanted properties first and then the left over properties are caught with the rest operator.

Works with arrays as well.

 const test = ['hey', 'hello', 'goodbye']; const [ first, ...rest ] = test; console.log(rest); 

You can try to work like this for destructuring arrays!

    let abc = {
      a: 'hello',
      b: 'hey',
      c: 'hi, there!'
    }


    let {a: x, b:y, c:z} = abc;

    console.log(x,y,z)  

// "hello"
   "hey"
   "hi, there!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM