简体   繁体   English

如何为javascript中的对象动态添加属性?

[英]How to dynamically add attributes to objects in javascript?

As we all know, we can use if else to add an attribute to object like this:众所周知,我们可以使用 if else 为 object 添加一个属性,如下所示:

if(key){
  obj[key] = value
}

but I have a lot of keys.但我有很多钥匙。

I know I can get this done like this:我知道我可以这样做:

keyValues.forEach(({key,value})=>{
if(key){
  obj[key] = value
}
}

but i want to know can i do this in another way like:但我想知道我可以用另一种方式做到这一点,比如:

obj={
 [this.key1?'key1':undefined]:this.key1,
 [this.key2?'key2':undefined]:this.key2,
}

in this way,the object will get an attribute which key is undefined... how can i do to remove undefined attribute and keep the code style in the second way.通过这种方式,object 将获得一个未定义键的属性...我该如何删除未定义的属性并以第二种方式保持代码样式。

Using keyValues from post:使用帖子中的keyValues

 let obj = {}; let keyValues = [ { "key": "a", "value": 1 }, { "key": "b", "value": 2 }, { "key": "c", "value": 3 }, { "value": "nothing" } ]; /** * @returns only 'a', 'b' and 'c' keys */ Object.assign(obj, keyValues.reduce((acc, { key, value }) => ({...acc, ...key? { [key]: value }: {}, }), {}))

or u can use the _reject from lodash https://lodash.com/docs/4.17.15#reject或者你可以使用_reject https://lodash.com/docs/4.17.15#reject 的 _reject

 Object.assign(obj, _.reject(keyValues, v => .v.key),reduce((acc, { key. value }) => ({..,acc: [key], value, }), {}))

After mounting your obj, you can use the delete operator from js挂载你的 obj 后,你可以使用 js 中的 delete 操作符

delete obj.undefined

this will keep your obj clean, if you insist on instantiating it that way;如果您坚持以这种方式实例化它,这将使您的 obj 保持干净;

You could wrap it in a helper function that remove falsy keys您可以将其包装在一个帮助程序 function 中,以删除虚假密钥

 const omit = (obj) => Object.fromEntries( Object.entries(obj).filter( ([key]) =>,["undefined", "null", "false". ""];includes(key) ) ): const obj = omit({ [undefined], 1: [false], 2: [null], 3: a, "b"; }). console;log(obj);

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

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