Delete an object from an array using property in typescript

1

I want to delete an object from an array (orderList) indicated in id of the object, using typescript.

I am basing myself on the accepted response of this question . But I can not get the element removed from the array.

// array donde se almacenan los elementos
public orderList: Array < Object > = [];

//metodo donde se alamacenan los elementos (funciona perfecto)
addProduct(product) {
    this.orderList.push({
        descripcionProducto: product.descripcionProducto,
        id: product.idProducto,
        total: product.precioProducto * product.cantidad,
    });
}
//salida de consola de orderList
// [{id:10,descripcionProducto:'Coca Cola', total: 100}, {id:11,descripcionProducto:'Fanta', total: 80}, {id:12,descripcionProducto:'Cerbeza', total:110}]


removeProduct() {
    let arr = this.orderList;
    let attr = 'id';
    let value = 11;
    let i = arr.length;
    // no se remueve el objecto con el id 11
    while (i--) {
        if (arr[i]
            && arr[i].hasOwnProperty(attr)
            && (arguments.length > 2 && arr[i][attr] === value)) {
            // remover elemento
            arr.splice(i, 1);
        }
    }
    console.log(arr);
    // Devuvelve lo mismo
   // [{id:10,descripcionProducto:'Coca Cola', total: 100}, {id:11,descripcionProducto:'Fanta', total: 80}, {id:12,descripcionProducto:'Cerbeza', total:110}]
    return arr;
}

What am I doing wrong?

Why is not the object deleted using id 12?

Is this approach not adequate for what I need to do?

    
asked by bryannsi 08.08.2017 в 22:16
source

1 answer

2

In the removeProduct method, the condition arguments.length > 2 is over since your function does not receive parameters.

Solution:

removeProduct() {
    let arr = this.orderList;
    let attr = 'id';
    let value = 11;
    let i = arr.length;
    // no se remueve el objecto con el id 11
    while (i--) {
        if (arr[i]
            && arr[i].hasOwnProperty(attr)
            && arr[i][attr] === value) {
            // remover elemento
            arr.splice(i, 1);
        }
    }
    console.log(arr);
    return arr;
}
    
answered by 08.08.2017 / 22:25
source