javascript - How to split string dynamically then return as array - Stack Overflow

For example, I have this stringrecipe.Tags = "Filipino Cuisine,Easy";and I want to convert it

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] },
              ];
Share Improve this question edited Feb 4, 2021 at 0:39 Len asked Jan 22, 2018 at 2:02 LenLen 5541 gold badge16 silver badges33 bronze badges 1
  • 2 this isn't an AngularJs issue, it's a JavaScript question. – Claies Commented Jan 22, 2018 at 2:12
Add a ment  | 

3 Answers 3

Reset to default 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./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}
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744964733a4603607.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信