简体   繁体   English

如何有条件地向对象添加属性

[英]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?我已经读过这篇在 Javascript 中,如何有条件地向对象添加成员? 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.将此视为在结构上类似于使用条件运算符 ( ?: ) 与使用if块之间的区别。 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块的用途:

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.没有理由避免使用if块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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