Loredra L Loredra L -5 years ago 151
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


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 Source

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 = [];

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download