Home > Back-end >  Passing a variable that holds JSON acts differently when in '{}' - why?
Passing a variable that holds JSON acts differently when in '{}' - why?

Time:04-06

I am writing a CLI application with Nodejs. The user sees a list of items and selects one that they want to be removed. The list they see is generated via a JSON file. The JSON file has one property with an array of actions:

{    

 "actionList":[
     "Action 1","Action 2","Action 3","Action 5","Action 6"]    
}    

Their input triggers an item to be removed and the file to be re-written with the updated list with fs.writeFileSync.

Question

When I write to the file WITHOUT {}, it writes the array to the JSON file without the property actionList:

The code:

fs.writeFileSync(
    path.join(__dirname, "./.todo.json"),
    JSON.stringify( actionList , null, 4)
  );

The result:

     ["Action 1","Action 2","Action 3","Action 5","Action 6"]

But when I use {} around actionList, I get the JSON file with the actionList property.

The code:

fs.writeFileSync(
    path.join(__dirname, "./.todo.json"),
    JSON.stringify({ actionList }, null, 4)
  );

The result:

"actionList":[
         "Action 2","Action 3","Action 5","Action 6"]    
    } 

What exactly is the {} doing in this case?

CodePudding user response:

{ actionList } is the same as { "actionList": actionList }

It is ES6 property shorthand.

Refer to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#new_notations_in_ecmascript_2015

Another example: https://alligator.io/js/object-property-shorthand-es6/

So the {} adds another layer around your object, with a key "actionList" and the value of the variable actionList.

  • Related