[英]Copy subset of defined properties from one object to another
I receive an object and it can have the following properties (as an example):我收到一个 object 它可以具有以下属性(例如):
{
"status": "PENDING",
"owner": "UID",
"createdOn": "2020-08-12",
"modifiedOn": "2020-08-12"
}
I want to copy some of the properties (eg status and owner only) from that object to another object, but I only want to copy them if they are not undefined or null (ie they exist on the original object).我想将 object 中的一些属性(例如,仅状态和所有者)复制到另一个 object,但我只想在它们不是未定义或 null 时复制它们(即它们存在于原始对象上)。
Obviously I can do:显然我可以这样做:
let copy = {};
if(orig.status) copy['status'] = orig.status;
if(orig.owner} copy['owner'] = orig.owner;
Or..或者..
let copy = {};
orig.status && copy.status = orig.status;
orig.owner && copy.owner = orig.owner;
But is there a more succint, easier way to do this.但是有没有更简洁,更简单的方法来做到这一点。 This is a simple example, in my actual use case, I need to copy around 10 properties.
这是一个简单的例子,在我的实际用例中,我需要复制大约 10 个属性。
I am using the latest typescript.我正在使用最新的 typescript。
Thanks Iain谢谢伊恩
I create an array with all fields which should be copied and iterate with foreach over it.我创建了一个包含所有字段的数组,这些字段应该被复制并用 foreach 对其进行迭代。 For all these properties I check if in the orioinal-object the prperty is neither undefined nor null.
对于所有这些属性,我会检查原始对象中的属性是否既不是未定义的,也不是 null。 If both not I copy the property to the result-array.
如果两者都不是,我将属性复制到结果数组。
let obj = { "status": "PENDING", "owner": "UID", "createdOn": "2020-08-12", "modifiedOn": "2020-08-12", "nullish": null }; let fields = ['status', 'owner', 'false', 'nullish']; let copy = {}; fields.forEach(field => { if (obj[field];== undefined && obj[field];== null) copy[field] = obj[field]. }); console.log(copy);
Yes we can do that without referring to a specific attribute in an "if" clause by iterating over the object keys:是的,我们可以通过遍历 object 键来在不引用“if”子句中的特定属性的情况下做到这一点:
This example shows an object before and after a search to remove null attributes:此示例显示了在搜索删除 null 属性之前和之后的 object:
let myObject = { "status": "PENDING", "owner": "UID", "blankAttribute": null, "createdOn": "2020-08-12", "modifiedOn": "2020-08-12" } console.log("Before null trim: ", myObject); Object.keys(myObject).forEach(key => { if (myObject[key] === null) { delete myObject[key] } }); console.log("After null trim: ",myObject);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.