How I spent hours displaying objects from chips into a dropdown

The task of copying an object in JavaScript

Yesterday, I had a simple user story at work. The user story was to simply display data that the user selects on an Angular Material chips input into an Angular Material dropdown.

To be honest the data I was working with was a complex object from a database.

Display objects user selected in matchip into a dropdown

Yet, at the core, the task was simply copying objects.

But for simplicities sake, we will just work with a simple fruit object and try to emulate the task here.

So like I said, the task was simply filtering the user-selected objects from DB and having a separate copy. Why a separate copy? Because I needed to maintain the objects selected in the dropdown too.

At the time I was just working with the same object, and the changes on the chips would be reflected in the dropdowns. This was frustrating me and wasting my time.

Until I realize copying an object is not just an assignment operation.

Copying an object could waste your time

Let’s see this as an example:-

const fruit = {
 name: "Banana";
 price: 23;

Copying an object using spread operator

The spread operator ... is technically used to pass all values of arrays of objects. Hence, what we are doing here is to pass all the key:value pairs from the original object into the selectedFruit object.

const selectedFruit = {

Copying an object using assign method

Just like the creat method Object we saw last time, the assign method is used to shallow copy one object into another. And, It has two arguments, the target, and the source object.

const selectedFruit = Object.assign({}, fruit);

Your subscription could not be saved. Please try again.
Your subscription has been successful.

Learn Modern JS, CSS, & PHP

Subscribe to learn modern PHP in the most simple way.