简体   繁体   中英

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(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.

Using keyValues from post:

 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

 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

delete obj.undefined

this will keep your obj clean, if you insist on instantiating it that way;

You could wrap it in a helper function that remove falsy keys

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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