Home > Back-end >  how to extract multiple key and value from a single string in TypeScript?
how to extract multiple key and value from a single string in TypeScript?

Time:01-04

i have a string which contains multiple key and value inside it.

bodyString = "Product ID:\\nPDAZ03015022\\n\\nAddress:\\nUnit 3A, Block A, Palm Spring Condominium\\n\\nProduct Price (in CP): 5000\\n\\nProcessing Fee (in CP): 22000\\n\\nTax Fee (if any): 5CP",

now i want to extract the key-value pair as below.


bodyObject = 
{
  "Product ID": "PDAZ03015022",
  "Address": "Unit 3A, Block A, Palm Spring Condominium",
  "Product Price (in CP)": "5000",
  "Processing Fee (in CP)": "22000",
  "Tax Fee (if any)": "5CP"
}

how can i achieve this in TypeScript?

CodePudding user response:

not sure whether the below code can help.

var bodyString = "Product ID:\\nPDAZ03015022\\n\\nAddress:\\nUnit 3A, Block A, Palm Spring Condominium\\n\\nProduct Price (in CP): 5000\\n\\nProcessing Fee (in CP): 22000\\n\\nTax Fee (if any): 5CP";

var bodyObject = bodyString.split("\\n\\n") // each line
        .map(s => s.split(":")) // split by :
        .reduce((m,s)=> { // reduce to object.
           m[s[0]]=s[1].replace("\\n","").trim(); 
          return m;
        },{});
 console.log(bodyObject);

CodePudding user response:

One way you could achieve this is by using a regular expression to extract the key-value pairs from the string

Here's an example of how you could do this:

const bodyString = "Product ID:\nPDAZ03015022\n\nAddress:\nUnit 3A, Block A, Palm Spring Condominium\n\nProduct Price (in CP): 5000\n\nProcessing Fee (in CP): 22000\n\nTax Fee (if any): 5CP";

const regex = /([^:\n] ):\s*([^\n] )/g;
let match;
const bodyObject: { [key: string]: string } = {};
while (match = regex.exec(bodyString)) {
  bodyObject[match[1]] = match[2];
}
console.log(bodyObject);

CodePudding user response:

string.split on the newline char will give you close to what you are looking for. You'll need a common separator between each of the values you want to return, something that will definitively tell you where each object starts/ends.

Google is also a good option for things like this.

CodePudding user response:

Here is one way you could do it:

const bodyString = "Product ID:\nPDAZ03015022\n\nAddress:\nUnit 3A, Block A, Palm Spring Condominium\n\nProduct Price (in CP): 5000\n\nProcessing Fee (in CP): 22000\n\nTax Fee (if any): 5CP";

const bodyObject = {};

const lines = bodyString.split("\n");
for (let i = 0; i < lines.length; i  = 2) {
  const key = lines[i];
  const value = lines[i   1];
  bodyObject[key] = value;
}

console.log(bodyObject);

This will split the string into an array of lines, and then iterate over the lines in pairs, adding the key-value pairs to the bodyObject object.

  • Related