1

For example, I have this string

recipe.Tags = "Filipino Cuisine,Easy";

and I want to convert it to the array below.

$scope.tags = [{ Name: "Filipino Cuisine" },
               { Name: "Easy"},
              ];

I could use the code below but then it would only work for strings with 2 tags.

$scope.tags = [ { Name: recipe.Tags.split(',')[0] },
                { Name: recipe.Tags.split(',')[1] },
              ];
1
  • 2
    this isn't an AngularJs issue, it's a JavaScript question. Commented Jan 22, 2018 at 2:12

3 Answers 3

3

You can directly use .split and .map together to obtain an array and convert to array of objects

var recipe = {};
recipe.Tags = "Filipino Cuisine,Easy";
arr = recipe.Tags.split(',').map(function(item) {
  return {name: item};
});
 console.log(arr);
 

DEMO

var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope){
    var recipe ={};
    recipe.Tags = "Filipino Cuisine,Easy";
    $scope.tags = recipe.Tags.split(',').map(function(item) {
    return {name: item};
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp" ng-controller="testCtrl">
 <li ng-repeat="tag in tags">
   <h1> {{tag.name}}</h1>
 </li>
</body>

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

Comments

2

What i would do is save the tags in an array then iterate it to have your scope.tags. Like this:

var arrTags = recipe.Tags.split(',');
$scope.tags = [];

for(var i in arrTags) {
    var obj = {Name : arrTags[i]};
    $scope.tags.push(obj);
}

1 Comment

You can combine these separate process into one using code below
0

You can use Lodash library and chain _.split and _.map to obtain an array of object.

var str = 'Filipino Cuisine,Easy',
myObj = _.map(_.split(str,','),(value)=>{
  return {Name:value}
});

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.