Destructuring for Array-like objects

# Sultan (5 years ago)

Afford array destructuring to Array-like objects.

const [a, b] = {0: a, 1: b, length: 2}
# Ranando King (5 years ago)

Why is that any different or better than

const [a, b] = [a, b]

?

# Frederick Stark (5 years ago)

This already works with an iterator, because array destructuring uses the iterator protocol

const [a, b] = {
  0: "ayy",
  1: "bee",
  length: 2,
  *[Symbol.iterator]() {
    let i = 0;
    while (i < this.length) {
      yield this[i]
      i++
    }
  },
};
# Jordan Harband (5 years ago)
const [a, b] = Array.from(anyArraylikeObject);
# guest271314 (5 years ago)

If gather the expected result correctly object destructuring can be used

const {0: a, 1: b} = {0: "a", 1: "b", length: 2}

Alternatively, using Object.values() to get the values of the object as an Array

const [a, b] = Object.values({0: "a", 1: "b", length: 2})
# J Decker (5 years ago)

On Fri, Mar 22, 2019 at 10:32 AM guest271314 <guest271314 at gmail.com> wrote:

If gather the expected result correctly object destructuring can be used

const {0: a, 1: b} = {0: a, 1: b, length: 2}
var a = "testa", b="testb"; const {0: c, 1: d} = {0: a, 1: b, length: 2}

results in a const 'c' and const 'd' created with the values of a and b.

shouldn't it have created a variable '0' and '1' ?

# guest271314 (5 years ago)

shouldn't it have created a variable '0' and '1' ?

No. See Assigning to new variable names developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Assigning_to_new_variable_names

A property can be unpacked from an object and assigned to a variable with a different name than the object property.