Issue
I have this code as an example :
productsWithCategory$ = combineLatest([
this.products$,
this.productCategoryService.productCategories$
]).pipe(
map(([products, categories]) =>
products.map(product => ({
...product,
price: product.price ? product.price * 1.5 : 0,
category: categories.find(c => product.categoryId === c.id)?.name,
searchKey: [product.productName]
} as Product))
),
shareReplay(1)
);
I want to know how this part works with the spread operator ... ?
products.map(product => ({
...product,
price: product.price ? product.price * 1.5 : 0,
category: categories.find(c => product.categoryId === c.id)?.name,
searchKey: [product.productName]
} as Product)
as far as I understand the operator ... will copy the old object properties to a new object, but why when we add price again it still works ? doesn't it mean that now we have 2 properties "price" in that object ?
Solution
From what I understand the spread operator works both to add new keys to an object and to overwrite the keys it already has.
I imagine a product object like this:
product = {
price: 0,
category: a
};
Now we copy the object with the spread operator:
const product2 = {...product};
Now you have another object (in another memory location) with the same content as product.
Now we create a new object with other values with the spread operator:
const produc3 = { ...product, price: 1, category: b };
Now you have an object that has the same keys as the original but with other values.
Now we add a new key to the object:
const product4 = { ...product, name: 'car'};
Now you have an object that has the same keys as the original object, plus the name key.
You will never have an object with 2 keys the same.

Tested in the chrome console, if you try to define an object with two equal keys only the last key of the definition prevails.
Answered By - JuanPabloAmador
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.