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

admin2025-04-18  0

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}
});
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744964734a277127.html

最新回复(0)