Sevrene
Sevrene

Reputation: 53

Node.js - Using template literals outside of strings

I am reading line by line from a file and assigning each line to a keyed array. My files have each line beginning with their key (e.g name=,text=). I am wanting to assign each line to an array without having to manually type out each key.

example:

rd.on('line', function(line) {
   line = line.split('=');
   let key = line[0];
   line.shift();
   line = line.join(' ');
   array.name = line;
   // ... Next loop
   line = line.split('=');
   let key = line[0];
   line.shift();
   line = line.join(' ');
   array.text = line;
});

Which is NOT what I want

As far as I know template literals are only usable within `'d strings (console.log(${key})), though I am hoping there is some way around this that I was unable to find through searching.

The code that I want to work is here:

rd.on('line', function(line) {
   line = line.split('=');
   let key = line[0];
   line.shift();
   line = line.join(' ');
   array.${key} = line;
});

I am aware that array.${key} is invalid syntax and I am hoping someone here has some insight on how I would go about achieving what I am wanting.

Thanks in advance!

Upvotes: 0

Views: 144

Answers (3)

Sanka Darshana
Sanka Darshana

Reputation: 1421

Use array[key] where array is actually a dictionary.

Upvotes: 1

The Witness
The Witness

Reputation: 920

Would this do?

const data = {}; // I found name `array` confusing
rd.on('line', function(line) {
   const [key, ...rest] = line.split('=');
   data[key] = rest.join(' ');
});

One thing though, you are splitting with = but joining with (space character) but maybe this is intentional.

Upvotes: 1

mathhulk
mathhulk

Reputation: 50

If I understand the question correctly, you want to use an Object and not an Array to store the lines based on a specific key.

// initiate the Object
let lines = {};

rd.on('line', function(line) {
   line = line.split('=');
   let key = line[0];
   line.shift();
   line = line.join(' ');

   lines[key] = line;
});

You can read more about Object basics here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Upvotes: 1

Related Questions