0

Is there a way to destructure the "First shop" value in one go from this array?

const myArr = [
  {
    name: 'John',
    age: '28',
    hobbies: ['coding', 'chess', 'cards', 'reading'],
    address: {
      city: 'Some city',
      province: 'Some province',
      country: 'Some country',
    },
    places: {
      coffeeShops: ['First shop', 'Second shop', 'Third shop'],
    },
  },
];

Extracting the object from the array first actually works but I want to destructure from the array itself.

This works:

const obj = myArr[0];

const {
  places: {
    coffeeShops: [first],
  },
} = obj;

console.log(first);

But I can't seem to do it when the object is inside the array. Is that possible in JS?

10
  • You already show in your snippet how to destructure a value (first) out of an array positionally, did you try applying that to the root myArr too? Commented Aug 8, 2022 at 22:58
  • Yes it didn't work Commented Aug 8, 2022 at 22:58
  • Are you sure? Seems to work fine in my console. What specifically did you try, and how exactly did it not work? Update the minimal reproducible example. Commented Aug 8, 2022 at 22:58
  • Try this. typescriptlang.org/play?#code/… Commented Aug 8, 2022 at 23:00
  • Actually this time it worked. I promise it wasn't working before. const [ { places: { coffeeShops: [x], }, }, ] = myArr; Commented Aug 8, 2022 at 23:00

1 Answer 1

2

Putting the object in square brackets works:

const myArr = [
  {
    name: 'John',
    age: '28',
    hobbies: ['coding', 'chess', 'cards', 'reading'],
    address: {
      city: 'Some city',
      province: 'Some province',
      country: 'Some country',
    },
    places: {
      coffeeShops: ['First shop', 'Second shop', 'Third shop'],
    },
  },
];

const [
  {
    places: {
      coffeeShops: [first],
    },
  }
] = myArr;

console.log(first);

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.