0

My text file contains one small array (for simplicity here) of two objects as shown in array1. I want to load this text file and manipulate the array in further downstream steps. When it loads, it says it is a string, and as such prohibits array manipulation. How can load and manipulate my array after it loads?

var request = require('request');
var cheerio = require('cheerio'),
var fs = require('fs');

array1 = fs.readFileSync('smallArray.txt', 'utf8');
console.log(typeof array1);
//logs string!! 

var array2 = [{"username":"one","name":"158","EF":40.745954}, {"username":"two","name":"216","EF":24.016202}; 
console.log(typeof array2);
// logs object!!
2
  • 1
    Always include the language you're using in your tags. Commented Sep 3, 2016 at 1:19
  • ...also, tags like "array" and "fs" generally aren't useful because they aren't specific to your language and library -- "fs" can mean "filesystem", for instance, it doesn't mean the node.js fs library universally enough that someone can search for the fs tag in StackOverflow and get a useful result (which is the kind of thing that tags here are meant to be good for). Commented Sep 3, 2016 at 1:21

2 Answers 2

1

If smallArray.txt contains valid JSON, all you need to do is parse the contents:

array1 = JSON.parse(fs.readFileSync('smallArray.txt', 'utf8'));
Sign up to request clarification or add additional context in comments.

Comments

1

If the data in the file is valid JSON and you rename smallArray.txt to smallArray.json, you can just use require() and it will automatically parse it like this:

var array1 = require('smallArray.json');

1 Comment

@AttonRand - Since it appears you may be new here, if this answered your question you can indicate that to the community by clicking the green checkmark to the left of the answer to mark it as the best answer. This will also earn you some reputation points for following the proper procedure here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.