1

I have a JSON file "jFile" in the following format:

{
  "Entry1": null,
  "Entry2": "SomeValue"
}

And some node.js in the following format correctly updates the files:

jFile.Entry1= "SomeText";
fs.writeFileSync( "jFile.json", JSON.stringify(jFile, null, 2), "utf8");

However, if I do:

var testEnt = 'Entry' + 1;
jFile.testEnt = "SomeText";
fs.writeFileSync( "jFile.json", JSON.stringify(jFile, null, 2), "utf8");

The script runs without error, but never updates 'Entry1'. I have tried referencing it in a few ways (jFile.[testEnt] for example), and I get various new and interesting ways it doesn't work.

My questions are:

  1. Why? I understand that the script is not understanding that the 'testEnt' is not correctly understanding that I now mean this as a reference, and not a string, but I don't understand what I can do about it.
  2. How do I dynamically reference entries this way? I'd like to make the script flexible, but can't seem to find information on how to do this in particular.
HDCerberus
  • 2,113
  • 4
  • 20
  • 36

4 Answers4

2

In your example you wrote:

jFile.[testEnt]

The correct syntax is:

jFile[testEnt]

You are correct in the way you are trying to dynamically access and edit object properties, but you have that minor syntax error.

Haris Bouchlis
  • 2,366
  • 1
  • 20
  • 35
1

To update an object with a key inside a var you can do this:

obj[varKey] = 'what you want';

For your need:

var testEnt = 'Entry' + 1;
jFile[testEnt] = "SomeText";
fs.writeFileSync( "jFile.json", JSON.stringify(jFile, null, 2), "utf8");
0

You need to do like this:

const fs = require('fs');
const jFile = require('./jFile.json');

jFile.Entry1= "SomeText";

fs.writeFileSync( "jFile.json", JSON.stringify(jFile, null, 2), "utf8");

const testEnt = 'Entry' + 6;
jFile[testEnt] = "SomeText";
fs.writeFileSync( "jFile.json", JSON.stringify(jFile, null, 2), "utf8");

The mainpoint is here: jFile[testEnt] = "SomeText";

OUTPUT:

{
  "Entry1": "SomeText",
  "Entry2": "SomeValue",
  "Entry6": "SomeText"
}
Dave
  • 1,912
  • 4
  • 16
  • 34
-1

Try this it might help you.

var testEnt = 'Entry' + 1;
jFile[testEnt] = "SomeText";
fs.writeFileSync( "jFile.json", JSON.stringify(jFile, null, 2), "utf8");
narayansharma91
  • 2,273
  • 1
  • 12
  • 20