Home > Blockchain >  Converting text file to keys and value pairs
Converting text file to keys and value pairs

Time:12-11

so i have this text file that i want to convert into an javascript object The text file is the data of a private api

My text file:

Kevin
25
Mary
24

I want the result like this

{
Kevin: "25"
Mary: "24"
}

CodePudding user response:

import fs from 'fs'

// ...

const data = fs.readFileSync('/path/to/file'),
const rawLines = data.split(/\r?\n/) // Turn file into array of lines, considering input file might use windows or UNIX style carriage returns.
const object = rawLines.reduce((parsed, currentLine, index) => {
   if (((index   1) % 2) !== 0) return parsed // If we are on a entry on lines 1,3,5,7 etc, then don't need to do anything because next loop can backreference
   return { ...parsed, [rawLines[index - 1]]: currentLine} // We are on lines 2,4,6,8 etc and so now we can populate the object, by backreferencing the previous line and setting the value as the current one
}, {})

// ...

console.log(object)

enter image description here

  • Related