Home > Blockchain >  how to conver the array of undefined to a array of string
how to conver the array of undefined to a array of string

Time:04-20

I trying to pass the array value from frontend to the backend, while transmitting the value i facing some errors

this is my response data

{
  sender: 'venkat',
  numbers: '[919361667266, 919361667266, 919361667266, 919361667266]',
  message: 'hiii'
}

I need to convert this number data this '[919361667266, 919361667266, 919361667266, 919361667266]'

to

'["919361667266", "919361667266", "919361667266", "919361667266"]'

the error i faced while parsing

const numbers = JSON.parse(req.body.numbers);


(node:27058) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token @ in JSON at position 13
    at JSON.parse (<anonymous>)
    at /Users/

CodePudding user response:

Frontend is sending '[919361667266, 919361667266, 919361667266, 919361667266]'

What you can do is convert that string to an array of strings: response.numbers.split(/\D /).filter(s => !!s)

Code:

const response = {
  sender: 'venkat',
  numbers: '[919361667266, 919361667266, 919361667266, 919361667266]',
  message: 'hiii'
}
const numbers = JSON.stringify(response.numbers.split(/\D /).filter(s => !!s))
const str = JSON.stringify({
  ...response,
  numbers
})
const obj = JSON.parse(str)

console.log('Result Str: ', str)
console.log('Result Obj: ', obj)

CodePudding user response:

You are not sending proper JSON. JSON used double quotes around the key and string values

{
  "sender": "venkat",
  "numbers": "[919361667266, 919361667266, 919361667266, 919361667266]",
  "message": "hiii"
}

Alternatively, you could stringify your object

const payload = JSON.stringify({
  sender: 'venkat',
  numbers: '[919361667266, 919361667266, 919361667266, 919361667266]',
  message: 'hiii'
});

CodePudding user response:

After JOSN.parse the numbers param be an array of numbers, this is the case in the response because the server is sending an array of numbers. So you can either handle it in the server side or the client side

At Server Side

Before sending response stringily the values in the numbers array

numbers.map(val => val.toString())

OR

At Client Side

Parse it and convert it to string

JSON.parse(numbers).map(val => val.toString())

  • Related