2

I am trying to swap two object values in JavaScript using the [] = [] method, but my below code fails with an error saying "message": "Uncaught TypeError: Cannot set property '9' of undefined",

let dataObj={"reg_price":2, "reg_price_alt":5, "ex":9}
console.log("before: ", dataObj)
[dataObj.reg_price, dataObj.ex] = [4, 5];
console.log("after: ", dataObj)

Is there some syntax I'm missing? I don't understand why this simple code does not work.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Martin
  • 1,336
  • 4
  • 32
  • 69
  • I can't swap object variables using this method? – Martin Mar 22 '21 at 21:11
  • I disagree because I would like to complete this task on a single line if possible, which is why for swapping two variables it would be simple to just use the line: `[dataObj.reg_price, dataObj.ex] = [dataObj.ex, dataObj.reg_price];` which works with variables not in an object – Martin Mar 22 '21 at 21:13
  • In destructuring assignment, the targets in the array have to be simple variable references. So you can't put object property references there. – Barmar Mar 22 '21 at 21:17
  • @Teemu I've tried using deconstructing syntax like `({ dataObj.reg_price, dataObj.ex } = { dataObj.reg_price: 10, dataObj.ex: 20 });` but it doesnt work – Martin Mar 22 '21 at 21:17
  • Wait, this syntax works fine. You're just missing a semicolon. – ggorlen Mar 22 '21 at 21:21
  • I tried with fixed parenthesis / bracket syntax but no fix: `{ dataObj.reg_price, dataObj.ex } = { dataObj.reg_price: 10, dataObj.ex: 20 };` – Martin Mar 22 '21 at 21:23
  • With complete correct syntax this method still does not work: ``` let dataObj={"reg_price":2, "reg_price_alt":5, "ex":9} console.log("before: ", dataObj) [dataObj["reg_price"], dataObj["reg_price_alt"]] = [dataObj["reg_price_alt"], dataObj["reg_price"]]; console.log("after: ", dataObj) ``` – Martin Mar 22 '21 at 21:25

1 Answers1

7

The syntax is fine. Add a semicolon to prevent the automatic semicolon insertion from thinking you want to do console.log(...)[...] instead of array destructuring:

let dataObj = {"reg_price":2, "reg_price_alt":5, "ex":9}
console.log("before: ", dataObj); // <-- semicolon
[dataObj.reg_price, dataObj.ex] = [4, 5]
console.log("after: ", dataObj)

I'd take this a step further and add semicolons after every line. Caveat emptor otherwise. Example of swapping values:

const o = {a: 0, b: 1};
console.log(o);
[o.a, o.b] = [o.b, o.a];
console.log(o);
ggorlen
  • 44,755
  • 7
  • 76
  • 106