0

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.

1
  • are you seeing any error in safari? Commented May 17, 2016 at 4:16

4 Answers 4

1

It may be due to compatibility issue of reduce() so use simple for loop instead

var data = 'excellent,very_good,good,poor';

var strArr = data != null ? data.split(',') : [],
  res = {};

for (var i = 0; i < strArr.length; i++)
  res[strArr[i]] = strArr[i];

document.write('<pre>' + JSON.stringify(res, 0, 3) + '</pre>');


Or check reduce polyfill option for old browser.

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

1 Comment

@VishnuSBabu : glad to help you
0

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

0

You might as well do it

var data = "excellent,very_good,good,poor".split(','),
    res = {};
angular.forEach(data, function(value, key){
   res[value] = value;
});
console.log(res);

I hope to be of assistance.

Comments

0

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
  var data = 'excellent,very_good,good,poor';
  var jsonfied = {
    dataObj: data.replace(/,$/, "").split(",").map(function(name) {
      return {
        name: name
      };
    })
  };
  $scope.master = jsonfied;
});
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>
  <div ng-app="myApp" ng-controller="formCtrl">
    Maser :- {{master}}
    <br/>
    <br/>
  </div>
</body>

</html>

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.