Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parsing error: Unexpected token, expected "," AND SyntaxError: Unexpected token '['

app.js

let ids = [1, 2, 3];

let obj = {};

for (let i in ids) {
  obj = { ...obj, ids[i]: "" };   
}

console.log(obj);

While executing the above code, I get the below error.

Parsing error: Unexpected token, expected ","

  4 |
  5 | for (let i in ids) {
> 6 |   obj = { ...obj, ids[i]: "" };  
    |                      ^
  7 | }
  8 |
  9 | console.log(obj);eslint

I get this error, when I hover the mouse above the line obj = { ...obj, ids[i]: "" }; in my VS Code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When I run the code using node, i.e on node app.js. I get the following error in my terminal :

obj = { ...obj, ids[i]: "" };  
                     ^

SyntaxError: Unexpected token '['
    at wrapSafe (internal/modules/cjs/loader.js:988:16)
    at Module._compile (internal/modules/cjs/loader.js:1036:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47

What am I doing wrong? I expect the value of obj at the end to be {1 : "", 2 : "", 3: ""}

>Solution :

There are several solutions.

  1. Wrap it around a bracket:
for (let i in ids) {
  obj = { ...obj, [ids[i]]: "" }; // Brackets make it act as a key name instead of something else
}
  1. The simple and easy way:
for (let i in ids) {
  obj[ids[i]] = ""; // This adds a value
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading