1

I am trying to learn how destructuring works and encountered a challenge. I destructured results into a data variable and I was wondering how I would further destructure itemsInCart and 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);

below is my output so far:

{
    itemsInCart: [{
            name: 'pizza',
            price: 74,
            qty: 1
        },
        {
            name: 'Pepper Soup',
            price: 32,
            qty: 2
        }
    ],
    buyerCountry: 'Rwanda'
} => undefined
2
  • 1
    Hi Martin, what is the desired output? MDN provides a great guide. Commented Aug 1, 2019 at 23:44
  • const {results: [{buyerCountry, itemsInCart}]} = makeArray(). console.log(buyerCountry, itemsInCart); Commented Aug 1, 2019 at 23:44

1 Answer 1

1

One approach would be to further destructure the data object that you've obtained by doing the following:

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

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

console.log(itemsInCart, buyerCountry);

This can also be reduced into a single line by the following:

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.