在Javascript中,如何有条件地将成员添加到对象?

本文翻译自:In Javascript, how to conditionally add a member to an object?

I would like to create an object with a member added conditionally. 我想创建一个有条件添加成员的对象。 The simple approach is: 简单的方法是:

var a = {};
if (someCondition)
    a.b = 5;

Now, I would like to write a more idiomatic code. 现在,我想编写一个更惯用的代码。 I am trying: 我在尝试:

a = {
    b: (someCondition? 5 : undefined)
};

But now, b is a member of a whose value is undefined . 但现在, b是一个成员a ,其值是undefined This is not the desired result. 这不是期望的结果。

Is there a handy solution? 有方便的解决方案吗?

Update 更新资料

I seek for a solution that could handle the general case with several members. 我寻求一个可以解决几个成员的一般情况的解决方案。

a = {
  b: (conditionB? 5 : undefined),
  c: (conditionC? 5 : undefined),
  d: (conditionD? 5 : undefined),
  e: (conditionE? 5 : undefined),
  f: (conditionF? 5 : undefined),
  g: (conditionG? 5 : undefined),
 };

#1楼

参考:https://stackoom.com/question/N6Ov/在Javascript中-如何有条件地将成员添加到对象


#2楼

I would do this 我会这样做

var a = someCondition ? { b: 5 } : {};

Edited with one line code version 用一个行代码版本编辑


#3楼

In pure Javascript, I cannot think of anything more idiomatic than your first code snippet. 在纯Javascript中,我想不出比您的第一个代码片段更惯用的东西。

If, however, using the jQuery library is not out of the question, then $.extend() should meet your requirements because, as the documentation says: 但是,如果不是不可能使用jQuery库,那么$ .extend()应该符合您的要求,因为如文档所述:

Undefined properties are not copied. 未定义的属性不会被复制。

Therefore, you can write: 因此,您可以编写:

var a = $.extend({}, {
    b: conditionB ? 5 : undefined,
    c: conditionC ? 5 : undefined,
    // and so on...
});

And obtain the results you expect (if conditionB is false , then b will not exist in a ). 并获得预期的结果(如果conditionBfalse ,那么b不会存在a )。


#4楼

I think your first approach to adding members conditionally is perfectly fine. 我认为您有条件添加成员的第一种方法是完全可以的。 I don't really agree with not wanting to have a member b of a with a value of undefined . 我真的不与不希望有一个成员同意ba具有的价值undefined It's simple enough to add an undefined check with usage of a for loop with the in operator. 使用in运算符使用for循环添加undefined检查非常简单。 But anyways, you could easily write a function to filter out undefined members. 但是无论如何,您可以轻松编写一个函数来过滤出undefined成员。

var filterUndefined = function(obj) {
  var ret = {};
  for (var key in obj) {
    var value = obj[key];
    if (obj.hasOwnProperty(key) && value !== undefined) {
      ret[key] = value;
    }
  }
  return ret;
};

var a = filterUndefined({
  b: (conditionB? 5 : undefined),
  c: (conditionC? 5 : undefined),
  d: (conditionD? 5 : undefined),
  e: (conditionE? 5 : undefined),
  f: (conditionF? 5 : undefined),
  g: (conditionG? 5 : undefined),
});

You could also use the delete operator to edit the object in place. 您也可以使用delete运算符在适当位置编辑对象。


#5楼

If the goal is to have the object appear self-contained and be within one set of braces, you could try this: 如果目标是使对象显示为独立对象并放在一组括号内,则可以尝试以下操作:

var a = new function () {
    if (conditionB)
        this.b = 5;

    if (conditionC)
        this.c = 5;

    if (conditionD)
        this.d = 5;
};

#6楼

This has long been answered, but looking at other ideas I came up with some interesting derivative: 长期以来,人们已经回答了这个问题,但是在研究其他想法时,我想到了一些有趣的派生词:

Assign undefined values to the same property and delete it afterwards 将未定义的值分配给同一属性,然后将其删除

Create your object using an anonymous constructor and always assign undefined members to the same dummy member which you remove at the very end. 使用匿名构造函数创建对象,并始终将未定义的成员分配给最终要删除的同一虚拟成员。 This will give you a single line (not too complex I hope) per member + 1 additional line at the end. 这将为您每个成员提供一行(我希望不太复杂),最后再增加一行。

var a = new function() {
    this.AlwaysPresent = 1;
    this[conditionA ? "a" : "undef"] = valueA;
    this[conditionB ? "b" : "undef"] = valueB;
    this[conditionC ? "c" : "undef"] = valueC;
    this[conditionD ? "d" : "undef"] = valueD;
    ...
    delete this.undef;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值