Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split and map array from comma separated string list in angularjs

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>
like image 938
Jonathan Solorzano Avatar asked May 20 '26 23:05

Jonathan Solorzano


2 Answers

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>
like image 115
Abdelrahman M. Allam Avatar answered May 23 '26 14:05

Abdelrahman M. Allam


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.

like image 24
Steve Campbell Avatar answered May 23 '26 14:05

Steve Campbell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!