Split and map array from comma separated string list in angularjs

19,558

Solution 1

I think if you look for output like this CENTURY, BADGER, EXO you just need to do so

  <li ng-repeat="p in products">
    <p>{{p.brands}}</p>
  </li>

I edit this to add filter could help add this filter

 .filter('customSplit', function() {
  return function(input) {
    console.log(input);
    var ar = input.split(','); // this will make string an array 
    return ar;
  };
});

And your HTML view modified to

   <li ng-repeat="p in products">
    <p ng-repeat="brand in (p.brands | customSplit)">{{ brand }}{{$last ? '' : ', '}}</p>
  </li>

Solution 2

Array.map is helpful when transforming arrays.

If you have a single of your starting "product", you can make it into an array like this:

var expandedProduct = product.brands.split(',').map(function(brand, index) {
  return {
    'name': product.name,
    'brand': brand.trim(),
    'cost': product.costs.split(',')[index].trim(),
    'vat_cost': product.vat_costs.split(',')[index].trim()
  }
});

You could build on that to transform an array of them.

Share:
19,558
Jonathan Solorzano
Author by

Jonathan Solorzano

Updated on June 04, 2022

Comments

  • Jonathan Solorzano
    Jonathan Solorzano almost 2 years

    I want to merge two lists that are comma separated, CENTURY, BADGER & 65, 85 to form an array like: [{name: 'CENTURY', price: '65'}, {name: 'BADGER', price: 85}], the lists are in an json object:

    {
        unit: '35 lb',
        brands: 'CENTURY, BADGER'
        prices: '65, 85'
    }
    

    So what I've done is a filter:

    angular
        .module( 'app.purchases.products' )
        .filter( 'mergeDetails', mergeDetails );
    
    function mergeDetails() {
        return function ( product ) {
            _.merge( product.brands, product.prices );//Using lodash, any suggestion?
            console.log('brands ', product.brands);
            return product.brands;//`_.merge` will add prices to brands
        }
    }
    

    I'd like to know how to apply the filter to an interpolation {{ }} so that I could get the array and use it in a ng-repeat, here's where it is used:

    <tr ng-repeat="product in products">
        <td>{{product.unit}}</td>
        <td>
            <!-- Here I should filter to ng-repeat the resulting array -->
            {{product.brands +' '+ product.prices}}
        </td>
    </tr>