简体   繁体   中英

How can I add a property to an object conditionally

I have read this In Javascript, how to conditionally add a member to an object? but in my case, it doesn't work.

I have the following situation:

angular.forEach(vm.someData.entities, entity => {
  ...(entity.type === "section" && { entity.styleFormats = entity[`${vm.activeTab}StyleFormats`]});
  entity.content = entity[`${vm.activeTab}Content`];
  entity.stateClasses = determinateStateClasses(false);
  entity.isNew = false;
});

The spread operator gives me a parsing error.

Don't use the spread operator here. That operator is used when constructing an object literal, which isn't what you're doing here. You're simply writing a line of code in a function.

You may be able to use && short circuiting to perform the intended operation:

entity.type === "section" && entity.styleFormats = entity[`${vm.activeTab}StyleFormats`];

But this is a little unclear. Normally this kind of short-circuiting is used when resolving to a value, not when performing an operation. Think of this as structurally like the difference between using the conditional operator ( ?: ) vs. using an if block. The former is not a drop-in substitute for the latter, they have their own uses.

In this case what you're looking to do is conditionally perform an operation within your function. That's exactly what an if block is for:

if (entity.type === "section") {
    entity.styleFormats = entity[`${vm.activeTab}StyleFormats`];
}

Basically, don't try to write the cleverest code possible, write the clearest code possible. There's no reason to avoid using an if block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM