Vishnu S Babu Vishnu S Babu - 5 months ago 9
AngularJS Question

How can i convert a comma seperated string to json object type using angular

As a beginner in angular js, I am struck to convert the comma separated string from MySQL db to json object of bellow type
input :

excellent,very_good,good,poor


output:

Object {excellent: "excellent", very_good: "very_good", good: "good",poor: "poor" }


I tried with



var data='excellent,very_good,good,poor';
if(data!=null){
data= data.split(',').reduce((res,x)=>{
res[x] = x;
return res
},{});
}
console.log(data);





It works but the problem is it doesn't support in Safari.

Answer

Here is a sample code, that should do the job:

var data = 'excellent,very_good,good,poor';
var item = '';
var result = {};

if(data !== null) {
  data = data.split(',');
  
  for(var i = 0; i < data.length; i++) {
    item = data[i].trim();
    
    result[item] = item;
  }
}

console.log(result);

Comments