Hi I just started learning JS. I want to put cart1 and cart2 together.
if (cart1) {
for (const key in data) {
main.push({
id: Math.random().toString(),
name: data[key].name
image: data[key].image
location: data[key].location,
});
}
}
if (cart2) {
for (const key in data) {
main.push({
id: Math.random().toString(),
name: data[key].name
image: data[key].image
});
}
}
I used ternary operator, but I don’t want cart2 have location property
if (cart2 || cart1) {
for (const key in data) {
main.push({
id: Math.random().toString(),
name: data[key].name
image: data[key].image
location: cart1? data[key].location : "",
});
}
}
>Solution :
You can optionally add a property by adding it to object and spreading it optionally.
... is the spread operator, which will spread all the properties inside { location: data[key].location } object ( there is only one property which is location ), and that happens only if the cards are not a falsy value ( not equal to null or undefined or a value can be falsy like zero for numbers ) the && operator check value to be truthy.
For more resources.
AND operator
Spread operator
if (cart2 || cart1) {
for (const key in data) {
main.push({
id: Math.random().toString(),
name: data[key].name,
image: data[key].image,
...(cart1 && { location: data[key].location }),
});
}
}