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
  • 1
    JSON.parse(employee_id) Commented Jun 13, 2019 at 5:36

3 Answers 3

2

Parse your result to JSON before comparison.

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

}

It might help you.

Sign up to request clarification or add additional context in comments.

Comments

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')
}

Comments

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){
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.