Loredra L Loredra L - 4 months ago 14
JSON Question

Javascript change an value of a JSON key from String to Array

I have an service that some time return data structure like this

params:value;


and then sometime return

params:[value1, value2];


I want to change if value is String (first case), then delete it and make an empty params:[]. How can I aechive it?

Answer

After you parse JSON you can use typeof operator to see if value is string and if it is change it to empty array [].

var data = {
  params: 'value'
}

if(typeof data.params === 'string') data.params = [];
console.log(data);

Comments