I have a text file which content looks like this
textFile = "NGGCVS3.scratch1.create,end_date="07/03/2025",pin="31742",scnum="2736289877",senum="250322602004999",SCRPREF="500",SUSP_F="0""
I want to convert this text file / string into a javascript object to match this format
const object = {
pin: '31742',
scnum: '2736289877',
senum: "250322602004999"
}
Please help me out
You can split the string by comma, filter out those string without the equal symbol, filter out the "unkown" keys and finally build the desired object by using the function Array.prototype.reduce.
The following logic should be used for each line in the file.
const textFile = `NGGCVS3.scratch1.create,end_date="07/03/2025",pin="31742",scnum="2736289877",senum="250322602004999",SCRPREF="500",SUSP_F="0"
NGGCVS3.scratch1.create,end_date="07/03/2025",pin="31742",scnum="2736289877",senum="250322602004999",SCRPREF="500",SUSP_F="0"`;
const keys = ["pin", "scnum", "senum"];
const result = textFile.split("\n").map(line => {
return line.split(",")
.map(str => str.split("="))
.filter(({length}) => length > 1)
.map(([key, value]) => ({[key]: value.replace(/"/g, '')}))
.filter((obj) => Object.keys(obj).some(key => keys.includes(key)))
.reduce((a, c) => ({...a, ...c}), {})
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }