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] },
];
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] },
];
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./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>
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);
}
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}
});