简体   繁体   中英

Dynamically Create Object Based on Key Values (undefined)

Is there a way to create an object in JavaScript only if certain keys are not undefined?

For example, suppose I have some network request that requires a payload:

const payload = {
    key1: 'value1',
    key2: 'value2',
    key3: 'value3'
};

Now, let's suppose that key2 and key3 are optional parameters to a function. If I do not pass those in, and they are left as undefined will the object become:

const payload = {
    key1: 'value1',
};

I'm thinking that maybe using Object.create(...) can help me with this?

Any thoughts? Thanks

Not sure if I get you right, but is something like this that you need?

 let payload = { key1: 'value1', key2: 'value2', key3: null, key4: undefined }; let clearObject = function clearObject(obj) { let newObj = {}; Object.keys(obj).forEach((key) => { if (obj[key]) { newObj[key] = obj[key]; } }); return newObj; }; console.log(clearObject(payload)); 

You can use array#reduce with Object#key . Iterate through each key and only add those keys whose value isn't null or undefined .

 let payload = { key1: 'val1', key2: 'val2', key3: null, key4: undefined }, result = Object.keys(payload).reduce((r,k) => { if(payload[k]) r[k] = payload[k]; return r; },{}); console.log(result); 

When the object is serialized, keys with undefined values will be stripped (relevant since we're talking about network packets). Until it is, a placeholder may exist for the missing keys in the object. This is probably implementation specific and shouldn't be relied on.

var makePacket = function(value1, value2, value3) {
    return { key1: value1, key2: value2, key3: value3 }
}

Calling this with only value1 supplied as in payload = makePacket('test') could give you the result:

payload = {
    key1: 'test',
    key2: undefined,
    key3: undefined
}

If the object is serialized and passed over the network there will be no information about the missing keys and it will be just:

payload = {
    key1: 'test'
}

The difference between the value having a place but being undefined and not existing at all is slightly academic, since your handling code should treat both conditions identically. But be assured that you're not wasting bandwidth on non-existent keys if your serializer is worth using.

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