1

I'm working on Api with nodejs and I want to convert string format [10,20] in to array.

for example

//my co worker sent me string

employee_id : [ 10, 20 ];

and I check

if(Array.isArray(employee_id) || employee_id instanceof Array){
}

It's not working

andI try to typeof employee_id; it's return string

How can I change format string to an array

  • 1
    JSON.parse(employee_id) – vlumi Jun 13 at 5:36
2

Parse your result to JSON before comparison.

const employees = JSON.parse(employee_id)
if(Array.isArray(employees) {

}

It might help you.

1

You can try with JSON.parse():

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

if(Array.isArray(JSON.parse(employee_id)) || JSON.parse(employee_id) instanceof Array){
}

Demo:

var obj = {employee_id : '[ 10, 20 ]'};

console.log(typeof obj.employee_id);//string

if(Array.isArray(JSON.parse(obj.employee_id)) || JSON.parse(employee_id) instanceof Array){
  console.log('array')
}

0

API returns JSON string, So You have to parse the string to JSON object to check the acutal data type.

if(Array.isArray(JSON.parse(employee_id)) || JSON.parse(employee_id) instanceof Array){
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.