一切正常,直到发生第二次接触为止。
TypeError: Cannot set property 'name' of undefined
因为构造函数中的默认联系人只有1次出现。有什么解决方法吗?
class Cust {
constructor(custData) {
this.address = {
countryCode: null,
address1: null,
address2: null,
city: null,
countrySubDivision: null,
postalCode: null
},
this.groupId = null;
this.contact = [{ name: null, phone: null }];
//this.contact.phone = custData.contact.phone
this.state = this._getState(custData.status || null);
this._setData(custData);
}
_getState(status) {
let state = (status == 'active' ? 'good' : 'bad');
return state;
}
_setData(data, prefix, index) {
let result;
for (let key in data) {
let value = data[key];
let valueIsNullOrEmpty = !value;
if (!valueIsNullOrEmpty && typeof value === 'object') {
if (Array.isArray(value)) {
value = value
.map((subProperty, index) => this._setData(subProperty, key, index))
.filter((subProperty) => Object.keys(subProperty).length > 0);
valueIsNullOrEmpty = value.length === 0;
continue;
} else {
value = this._setData(value, key);
valueIsNullOrEmpty = Object.keys(value).length === 0;
continue;
}
}
if (prefix) {
if (index >= 0) {
this[prefix][index][key] = data[key];
}
else {
this[prefix][key] = data[key];
}
}
else {
this[key] = data[key]
}
result = data[key];
}
console.log(JSON.stringify(this));
return result;
}
}
var custData = {
id: 1,
name: "Barr",
// groupId: 2,
status: "active",
address: {
countryCode: "USA",
address1: "123 main street",
address2: null,
city: "Chicago",
postalCode: "85001"
}, contact: [
{
phone: "222-222-2222"
},
{
name: "Tim"
}]
}
var cust = new Cust(custData);
答案 0 :(得分:1)
您正在递归地格式化数据,但始终尝试从this
更改突变数据,例如
this[key]
这将适用于深度1,但假设深度为5,它将变得复杂:
this[key1][key2][key3][key4][key5]
您明白了这一点(这就是您的代码实际失败的地方,访问了深度大于2的嵌套对象的属性)。
this
将永远无法使用。代替将对象修改为成方法(然后可以是函数),还可以通过返回新对象(使调试更加容易)来使其保持不变。
function format(obj) {
const result = {};
//...
return result;
}
然后,您可以轻松地使用嵌套对象调用format
。
从类内部可以称为:
Object.assign(this, format(data));