gpt4 book ai didi

javascript - ES6 类默认值与数组

转载 作者:行者123 更新时间:2023-12-02 23:43:36 25 4
gpt4 key购买 nike

一切正常,直到第二次发生接触。

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);

最佳答案

您正在递归地格式化数据,但您总是尝试从 this 更改变异数据,例如

  this[key]

这适用于深度 1,但对于深度为 5 的情况,它会变得复杂:

 this[key1][key2][key3][key4][key5]

您明白了(这就是您的代码实际上失败的地方,访问深度大于 2 的嵌套对象的属性)。

这个永远不会起作用。相反,您可以通过传递对象来修改方法(可以是一个函数),然后通过返回一个新对象(这将使调试更容易)来保持它不可变:

 function format(obj) {
const result = {};
//...
return result;
}

然后您可以轻松地使用嵌套对象调用format。从类内部可以调用为:

  Object.assign(this, format(data));

关于javascript - ES6 类默认值与数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55956291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com