Javascript 解构数组

Javascript Destructuring an array

我正在尝试了解解构的工作原理并遇到了挑战。我将结果解构为一个数据变量,我想知道如何进一步解构 itemsInCart 和 buyerCountry。

function makeArray() {
  return {
    results: [
      {
        itemsInCart: [
          {
            name: "pizza",
            price: 74,
            qty: 1
          },
          {
            name: "Pepper Soup",
            price: 32,
            qty: 2
          }
        ],
        buyerCountry: "Rwanda"
      }
    ]
  };
}

const {
  results: [data]
} = makeArray();

console.log(data);

以下是我目前的输出:

{
    itemsInCart: [{
            name: 'pizza',
            price: 74,
            qty: 1
        },
        {
            name: 'Pepper Soup',
            price: 32,
            qty: 2
        }
    ],
    buyerCountry: 'Rwanda'
} => undefined

一种方法是进一步解构您通过执行以下操作获得的 data 对象:

/* Your current destructuring */
const { results: [data] } = makeArray();

/* Additional destructuring step to get itemsInCard and buyerCountry */
const { itemsInCart, buyerCountry } = data;

console.log(itemsInCart, buyerCountry);

这也可以通过以下方式缩减为一行:

function makeArray() {
  return {
    results: [{
      itemsInCart: [{
          name: "pizza",
          price: 74,
          qty: 1
        },
        {
          name: "Pepper Soup",
          price: 32,
          qty: 2
        }
      ],
      buyerCountry: "Rwanda"

    }]
  }
};


const { results: [{ itemsInCart, buyerCountry }] } = makeArray();

console.log('itemsInCart:', itemsInCart);
console.log('buyerCountry:', buyerCountry);