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>
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With