如何动态创建JavaScript对象?按需合并插入对象的简洁实现
简洁实现动态对象属性插入的方案
你可以利用ES6的对象扩展运算符来实现需求,完全不需要依赖Object.assign,写法非常简洁:
let isThingTrue = true; let dynamicObjectItem1 = {"foo": "bar"}; let dynamicObject = { "item1": "stuff here", "item2": "stuff here", ...(isThingTrue ? dynamicObjectItem1 : {}), "item3": "stuff here" };
原理说明
- 当
isThingTrue为true时,...dynamicObjectItem1会把该对象的所有属性平展插入到目标对象中,最终dynamicObject会包含foo: "bar"属性; - 当
isThingTrue为false时,我们展开一个空对象{},这不会给目标对象添加任何额外属性,完全符合你的预期。
你之前写法失效的原因
直接在对象字面量里写三元表达式会触发语法错误,而如果直接放入dynamicObjectItem1变量,JavaScript会把变量名当作键名,生成嵌套对象(比如{ dynamicObjectItem1: { foo: "bar" } }),无法实现属性平展的效果。
如果需要处理多个动态对象的场景,同样可以用这种方式叠加:
let isThingTrue = true; let isAnotherThingTrue = false; let obj1 = {foo: "bar"}; let obj2 = {baz: "qux"}; let dynamicObject = { item1: "stuff here", ...(isThingTrue ? obj1 : {}), ...(isAnotherThingTrue ? obj2 : {}), item3: "stuff here" };
内容的提问来源于stack exchange,提问作者Derek Ball
相关产品推荐
相关产品推荐

