skip to Main Content

I have a string like this

var string = "1234|Tom|NYC|Student|Active"

and I want to map to something like in typescript NodeJS API

{  
  "Id": 1234,
  "Name": "Tom",
  "City": "NYC",
  "Title": "Student",
  "Status": "Active",
}

Here the key comes from a static set of keys that can be stored anywhere.

I tried converting string to array and tried .reduce, but I end up cannot get the desired results…
Can you please help out?

2

Answers


  1. An answer already exists to this question in this thread…

    But you would first convert your string into a key-value JavaScript object and then use the JSON.parse(keyValueObject).

    Login or Signup to reply.
  2. You can use .split() like this :

    let string = "1234|Tom|NYC|Student|Active"
    const id = string.split("|")[0]
    const name = string.split("|")[1]
    

    and then you create you object:

    const finalObj = {id,name}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search