3

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>
1

5 Answers 5

5

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>
Sign up to request clarification or add additional context in comments.

5 Comments

You misunderstood what I said, I want the opposite of that... I have the string like CENTURY, BADGER, EXO
you maybe need a to make filter split it
Why use a filter? Why not simply use brand in p.brands.split(',')?
brand in p.brands.split(',') is nice, I missed this one
I updated the question for a better understanding, check it out
3

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.

Comments

0

this should do it:

var transpose = function(obj){
    var result =[];
    for(key in obj){
        var aux = obj[key].split(",");
        for(i in aux){
            if(result[i]==null){
                result[i]={};
            }
            result[i][key]=aux[i].trim()
        }
    }
    return result
}

Comments

0

Personally I don't prefer filters as a solution for this problem, because as the term defines, its should be used for filtering/selecting the items to display. As Steve Campbell suggests, you should transform/map the products into your desired form. Demo

// flatten the pr0ducts into one array ...
vm._products = data.reduce(function (previous, current) {
                        return previous.concat(generateMergeList(current))
                    }, []);

// helper function to generate a list of product in a product data object
function generateMergeList(source) {
var result = [];
if (!source || !source.brands || !source.prices) {
    return result;
}

var _brands = source.brands.split(',');
var _prices = source.prices.split(',');

if (_brands.length !== _prices.length) {
    throw 'Number of items in brands and prices aren\'t the same...';
}

return _brands.map(function (elm, idx) {
    return {
        brand : elm,
        price : _prices[idx],
        unit : source.unit
    };
});
}

Comments

0
let arrayDefaultDeliveryDay = Array.from(this.defaultDeliveryDays.split(","));
let arrayDefaultDeliveryFoodType = Array.from(this.defaultDeliveryFoodType.split(","));
let arrayDefaultDeliveryStartTime = Array.from(this.defaultDeliveryStartTime.split(","));
let arrayDefaultDeliveryEndTime = Array.from(this.defaultDeliveryEndTime.split(","));

var deliveryDetails = [];

for(var i = 0; i<=arrayDefaultDeliveryDay.length-1; i++){
  deliveryDetails.push({
    foodType : arrayDefaultDeliveryFoodType[i],
    day : arrayDefaultDeliveryDay[i],
    startTime : arrayDefaultDeliveryStartTime[i],
    endTime : arrayDefaultDeliveryEndTime[i]
  })
}

console.log(JSON.stringify(deliveryDetails));

After a lot of research, Finally found the solution.

1 Comment

That Array.from is redundant, split returns an array. You can also replace i<=arrayDefaultDeliveryDay.length-1 with i<arrayDefaultDeliveryDay.length or even read arrayDefaultDeliveryDay.length before for loop and use i<someVariable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.