2

I'm setting one array equalls to another

        orders = [
           {
            'id': PROCESSING,
            'displayName': 'Processing'
           },
           {
            'id': SHIPPED,
            'displayName': 'Shipped'
           }
        ];

        cloneOrders = [];

setOrders() {
        this.orders.forEach((order: any) => {
                this.cloneOrders = order;
        });
    }

But when I try to get values of 'cloneOrders' in another funtion it return an empty array

getOrders(status, minutes) {
        this.cloneOrders .forEach((order: any) => {
                console.log(order);
        });
    }

Both functions are in a same component. Please help me how to resolve this thanks.

2
  • You ought to be pushing them into an array: this.cloneOrders.push(order);. Make sure cloneOrders is initialized. Commented Nov 12, 2018 at 9:54
  • The setOrders method loops through the orders array and assign current iteration item to cloneOrders array. So when the function returned, you'll have the last item of orders stored in cloneOrders not the complete array. Commented Nov 12, 2018 at 9:55

5 Answers 5

16

Try like this

setOrders() {
        this.cloneOrders= [...this.orders];
    }

Happy coding !!

Sign up to request clarification or add additional context in comments.

Comments

2

You need .push inorder to add items to the array,

this.orders.forEach((order: any) => {
       this.cloneOrders.push(order);
 });

better way to do that with ES6 using spread operator,

setOrders() {
        this.cloneOrders= [...this.orders];
}

Comments

1

If you want to do deep cloning -

let cloned = this.cloneOrders.map(x => Object.assign({}, x));

Comments

0

you are assigning every time new object from orders to cloneOrders, you need to push that orders in cloneOrders

setOrders() {
        this.orders.forEach((order: any) => {
                this.cloneOrders.push(order);
        });
    }

Comments

0

we can do using ES6 using spread operator

orders = [
 {'id': PROCESSING,'displayName': 'Processing'},
 {'id': SHIPPED,'displayName': 'Shipped'}
];

cloneOrders = [];

setOrders(){
  this.cloneOrders= [...this.orders];
}

Comments

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.