我这里有一个较旧的 Aura 方法,我想将其转换为现代 Javascript。由于某种原因,我不断得到不同的输出。我在递归(数据)之前控制台日志,然后在 getFieldNames() 函数之前控制台日志,并且“cur”不同。如果我一开始就记录“cur”,情况也会有所不同。我基本上希望 AURA 和 LWC 的日志是相同的,但 LWC 只有一个。
想法:我的目标是获取嵌套对象的值,但感觉他们过度设计了它。它可能就像点符号一样简单,然后循环该对象。只是感觉很奇怪。
let test = data.ContactTerritoryRelationship__c.Contact__r;
Object.keys(test).forEach(function (prop) {
console.log(test[prop]);
})
光环
formatNestedMetadata: function (data) {
let result = [];
let helper = this;
function recurse(cur, prop, attr) {
if (cur.hasOwnProperty("__attr__")) {
attr = cur["__attr__"];
delete cur["__attr__"];
}
for (let key of Object.keys(cur)) {
let value = cur[key];
if (typeof value != "object") {
// Our value is not an attribute, so stop recursing
cur["apiName"] = prop;
if (attr) {
cur["object"] = attr["sObjectType"];
if (prop.includes("Contact__r")) {
cur["label"] = attr["label"] == "Account ID" ? "Firm" : "" +
attr["label"];
} else {
cur["label"] = attr["label"];
}
} else {
cur["object"] = prop.includes("Contact__r")
? "Contact"
: "distributionterritory__c";
if (prop.includes("Contact__r")) {
**console.log('Aura', cur);**
cur["label"] = helper.getFieldName(cur["label"]);
} else {
cur["label"] = cur["label"];
}
}
result.push(cur);
break;
} else if (Array.isArray(value)) {
// Pass
} else {
// True if value is object
let newProp = prop && key ? prop + "." + key : key;
recurse(cur[key], newProp, attr);
}
}
}
recurse(data, "");
return result;
},
LWC版本
formatNestedMetadata(data) {
let result = [];
console.log(data);
//DATA MATCHES AURA VERSION UP UNTIL THIS POINT...
function recurse(cur, prop, attr) {
if (Object.prototype.hasOwnProperty.call(cur, "__attr__")) {
attr = cur.__attr__;
delete cur.__attr__;
}
for (let key of Object.keys(cur)) {
let value = cur[key];
if (typeof value != "object") {
// Our value is not an attribute, so stop recursing
cur.apiName = prop;
if (attr) {
cur.object = attr.sObjectType;
if (prop.includes("Contact__r")) {
cur.label = attr.label === "Account ID" ? "Firm" : "" + attr.label;
} else {
cur.label = attr.label;
}
} else {
cur.object = prop.includes("Contact__r")
? "Contact"
: "distributionterritory__c";
if (prop.includes("Contact__r")) {
**console.log('LWC', cur);**<-----------This logs differently now?
cur.label = this.getFieldName(cur.label);
} else {
// is this doing anything..
cur.label = cur.label;
}
}
break;
} else if (Array.isArray(value)) {
// Pass
} else {
// True if value is object
let newProp = prop && key ? prop + "." + key : key;
recurse(cur[key], newProp, attr);
}
}
}
recurse(data, "");
return result;
}
AURA 方法中的行
let helper = this;
和 cur["label"] = helper.getFieldName(cur["label"]);
将 this
保存在闭包中以供 recurse
函数使用。
LWC版本需要使用相同的方法。 LWC
this
中的 recurse
不再正确设置。
在不重建环境的情况下很难验证此建议,但似乎是一个起点。
最后,我同意,应该有一个更简单的方法。似乎设计过度了。