简体   繁体   English

有条件地向JavaScript对象添加属性

[英]Conditionally adding properties to JavaScript object

Is there a more concise or readable way of doing this? 有没有更简洁或可读的方式来做到这一点?

var foo={a:111,c:333, somePropertyThatShouldntBeAdded:'xxx'};
var myobj={x:1,y:2,z:3};
if(foo.a){myobj.a=foo.a;}
if(foo.b){myobj.b=foo.b;}
if(foo.c){myobj.c=foo.c;}

EDIT. 编辑。 Context why I am doing this is below. 我执行此操作的背景如下。

var obj={value:this.text,css:{color:'#929292',margin:'1px 0px'}};
if(this.width){obj.css.width=this.width;}
if(this.type){obj.type=this.type;}
if(this.id){obj.id=this.id;}
var input=$('<input/>',obj)

You could use a simple loop-based approach: 您可以使用基于循环的简单方法:

var foo={a:111,c:333, somePropertyThatShouldntBeAdded:'xxx'};
var myobj={x:1,y:2,z:3};

['a','b','c'].forEach(function(key) {
    if(key in foo) {
        myobj[key] = foo[key];
    }
});

Notice how I used the in keyword. 注意我如何使用in关键字。 Your current solution will not work if the value of a property is (eg) false or 0 . 如果属性的值为(例如) false0则您当前的解决方案将不起作用。

Additionaly, to get better solutions, provide some context: why are you conditionally copying properties? 另外,为了获得更好的解决方案,请提供一些上下文:为什么要有条件地复制属性? Perhaps you can avoid this to begin with. 也许您可以避免这种情况。

You can use the ternary operator like this: 您可以像这样使用三元运算符:

myobj.a = foo.a ? foo.a : undefined;

Though its not exactly the same as the if statement you have, because you'll have {a: undefined} instead of {} . 尽管它与if语句并不完全相同,因为您将使用{a: undefined}而不是{} The difference would show up if you ever enumerated the keys of your object. 如果您曾经枚举对象的键,则会显示出差异。

Edit: 编辑:

@hindmost has a good suggestion in the comments. @hindmost在评论中有很好的建议。 You could improve it further with underscore.js : 您可以使用underscore.js进一步改进它:

_.extend(myobj, _.pick(foo, ['a', 'b', 'c']));

You could use jQuery's extend , then delete the properties you don't want: 您可以使用jQuery的extend ,然后delete不需要的属性:

function extendExcept(sourceObject, targetObject, except) {
    var target = $.extend(sourceObject, targetObject);
    except.forEach(function(key) {
        delete target[key];
    });
    return target;
}

You could call it like: 您可以这样称呼它:

var foo={a:111,c:333, somePropertyThatShouldntBeAdded:'xxx'};
var myobj={x:1,y:2,z:3};
myobj = extendExcept(foo, myobj, ["somePropertyThatShouldntBeAdded"]);

Working Example 工作实例

var foo = {
    a: 111, 
    c: 333, 
    somePropertyThatShouldntBeAdded: 'xxx'
}; 

var myObj = {
    x: 1, 
    y: 2, 
    z: 3
}; 

for(var key in foo) {
    if(key === 'somePropertyThatShouldntBeAdded') {
        continue; 
    }
    myObj[key] = foo[key]; 
}

With the introduction of the spread operator in ES2018 you can do something like this. 随着ES2018中的点差运算符的引入,您可以执行以下操作。

const original = {
    first: null,
    second: 'truthy'
};

const conditionalObject = {
  ...( original.first && { first: original.first }),
  ...( original.second && { second: original.second })
};

In the conditionalObject we first check if the property we want to add from the original is truthy, if it is we spread that property with its value into the new object. conditionalObject我们首先检查要从original属性添加的属性是否为真,如果是,则将该属性及其值传播到新对象中。

If the property from the original object is falsy, the && short circuits and the property is never spread into the new object. 如果原始对象的属性是虚假的,则&&短路,并且该属性永远不会传播到新对象中。

You can read a more detailed explanation here 您可以在此处阅读更详细的说明

The new conditionalObject will look like this 新的conditionalObject将如下所示

{
    second: 'truthy'
}

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

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