0

I would like to know if it possible to deconstruct (in my case x) an array and create an alias in order to avoid issues with reserved keywords.

Here an example, but it gives me an error. Any idea how to solve it? Thanks

   const mk = (data) =>
      data.map((x, idx) => {
        const [a, b, for:xxx, d] = x
        return {
          a,
          b,
          for:xxx, // I want create an object with for property name
          d
        }
      })
2
  • 1
    Use quotation marks? { "for": xxx } Commented May 7, 2019 at 13:11
  • 2
    Just replace: const [a, b, for:xxx, d] = x with const [a, b, xxx, d] = x. jsfiddle.net/6974zk8o Commented May 7, 2019 at 13:16

2 Answers 2

3

You are mixing up objects and arrays. You are tying to use an alias on a array deconstruction.

If you deconstruct an array, there is no need for an alias

const x = [
  'a',
  'b',
  'd',
  'for',
];

const [
  a,
  b,
  d,
  xxx,
] = x;

console.log({
  a,
  b,
  xxx,
  d
});


If you are deconstructing an object, using for isn't a problem.

const x = {
  a: 'a',
  b: 'b',
  d: 'd',
  for: 'for',
};

const {
  a,
  b,
  for: xxx,
  d,
} = x;

console.log({
  a,
  b,
  xxx,
  d
});

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

Comments

1

In the context of an array, deconstructing for: xxx does not make any sense. This only works for an object having a for property (const {a, b, for: xxx, d } = x;).

xxx is simply the third element of the given array. The following might do it:

const mk = (data) =>
  data.map((x: any, idx: any) => {
    const [a, b, c, d] = x;
    return {
      a,
      b,
      for: c, // I want create an object with for property name
      d,
    }
  })

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.