简体   繁体   中英

destructing es6 in array push

i want to use something like destructing assignment in ES6 for having cleaner code but i dont know how to use it in something like pushing in array or anyway can is use it or something similar?. this sample code is in vue js :

result.map((item) => {
   this.virtualWallets.push({
      credit: item.credit,
      type: item.type,
      name: item.name,
      symbol: item.symbol,
      image: item.image,
      address: item.address,
      address_tag: item.address_tag,
      auto_transfer: item.auto_transfer,
   });
});

Try this code:

result.map((item) => {
  const {credit_formatted, type, name, symbol, image, address, address_tag, auto_transfer} = item;
  this.virtualWallets.push({
    credit: credit_formatted,
    type: type,
    name: name,
    symbol: symbol,
    image: image,
    address: address,
    address_tag: address_tag,
    auto_transfer: auto_transfer,
  });
});

or this:

result.map(({credit_formatted, type, name, symbol, image, address, address_tag, auto_transfer}) => {
  this.virtualWallets.push({
    credit: credit_formatted,
    type: type,
    name: name,
    symbol: symbol,
    image: image,
    address: address,
    address_tag: address_tag,
    auto_transfer: auto_transfer,
  });
});

And then you can remove unnecessary words, like this:

result.map(({credit_formatted, type, name, symbol, image, address, address_tag, auto_transfer}) => {
  this.virtualWallets.push({
    credit: credit_formatted,
    type,
    name,
    symbol,
    image,
    address,
    address_tag,
    auto_transfer,
  });
});

you can try something like this.

result.map(({credit_formatted, type, name, symbol, image, address, address_tag, auto_transfer}) => {
      this.virtualWallets.push({
        credit: credit_formatted,
        type,
        name,
        symbol,
        image,
        address,
        address_tag,
        auto_transfer,
      });
    });

Based on your comment to @Athish Murugan's answer:

You can also destructure like this:

let virtualWallet = this.virtualWallets.find(wallet => wallet.symbol === 'x');

const [name, symbol, credit, address_tag] = virtualWallet;

this.selectedVirtualWallet.name = name;
this.selectedVirtualWallet.symbol = symbol;
this.selectedVirtualWallet.credit = credit;
this.selectedVirtualWallet.address_tag = address_tag;;

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