Home > Net >  split array into multiple elements based on quantity property in angular
split array into multiple elements based on quantity property in angular

Time:03-08

My requirement is as below

array:

0:{name: 'test', qty: 3}
1:{name: 'test2', qty: 2}

I want to split array items based on quantity for eg.

0:{name: 'test', qty: 1}
1:{name: 'test', qty: 1}
2:{name: 'test', qty: 1}
3:{name: 'test2', qty: 1}
4:{name: 'test2', qty: 1}

I am doing like this

    let data = this.orders;
    let returndata=[];
    for( let i=0; i< data.length; i  ){
        const qty= data[i].qty;
        const order = data[i];
    for(let j=0; j<qty;j  ){
       order.qty=1;
       returndata.push(order);
     }
  }

It is working fine but when i show it in grid in angular and enter value in one of the row's textbox same value reflect in same name's other rows.

I think it is because rows are having same data that is why it reflect same data in each input box of same name?

My solution was to give unique sno. to each relative elements

 for(let j=0; j<qty;j  ){
       order.qty=1;
       order.sno=j 1;//tried this
       returndata.push(order);
     }

but this is working weird now each relative rows is having same sno. for eg. 2nd push override first element sno with 2. as below

 0:{name: 'test',sno=3, qty: 1}
1:{name: 'test',sno=3, qty: 1}
2:{name: 'test',sno=3, qty: 1}
3:{name: 'test2',sno=2, qty: 1}
4:{name: 'test2',sno=2, qty: 1}

Pls understand my problem and provide inputs

CodePudding user response:

This is actually a problem of copying by reference. Your code will work if you do this: returndata.push({...order}); This means that you are creating a new object that has no reference to the object in orders array. If your version of angular does not support spread syntax, you can always do it by using Object.create, like this: returndata.push(Object.create(order));

  • Related