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.

7
  • I can't swap object variables using this method? Commented Mar 22, 2021 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 Commented Mar 22, 2021 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. Commented Mar 22, 2021 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 Commented Mar 22, 2021 at 21:17
  • Wait, this syntax works fine. You're just missing a semicolon. Commented Mar 22, 2021 at 21:21

1 Answer 1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.