简体   繁体   English

根据键值动态创建对象(未定义)

[英]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? 仅当未定义某些键时,才可以使用JavaScript创建对象的方法吗?

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. 现在,让我们假设key2key3是函数的可选参数。 If I do not pass those in, and they are left as undefined will the object become: 如果我不传递它们,而将它们保留为undefined则该对象将变为:

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

I'm thinking that maybe using Object.create(...) can help me with this? 我在想也许使用Object.create(...)可以帮助我吗?

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 . 您可以将array#reduceObject#key Iterate through each key and only add those keys whose value isn't null or undefined . 循环访问每个键,仅添加值不为nullundefined那些键。

 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 = makePacket('test')提供的value1进行调用可以得到以下结果:

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. 但是请确保,如果值得使用串行器,则不会浪费带宽。

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

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