将字符串解析为数组然后返回字符串

时间:2019-07-05 10:56:57

标签: javascript arrays angular parsing stringify

我试图将对象“ this.model”填充为字符串,该字符串最初是由用户选择问卷中的复选框所填充的值的数组。

以下代码在用户单击复选框时处理事件 在用户两次单击同一复选框时开始填充数组并删除值。

public checked(check: QuestionnaireCheck): void {
    this.checkedOption = check;
    if(this.model[check.name] == undefined) {
        this.model[check.name] = [];
    }
    if(this.model[check.name].includes(check.value)) {
        let index = this.model[check.name].indexOf(check.value);
        if (index > -1) {
            this.model[check.name].splice(index, 1);
        }
    }
    else {
        this.model[check.name].push(check.value); 
    }
}

我试图将此数组更改为字符串值的尝试如下,即从字符串开始,然后处理数组操作,但将值返回为字符串,我不确定如何处理数组的初始未定义状态。

public checked(check: QuestionnaireCheck): void {
    let currentFeatures = this.model[check.name] || '';
    currentFeatures = JSON.parse(currentFeatures);

    if(currentFeatures.includes(check.value)) {
        let index = currentFeatures.indexOf(check.value);
        if (index > -1) {
            currentFeatures.splice(index, 1);
        }
    } else {
        currentFeatures.push(check.value); 
    }
    this.model[check.name] = JSON.stringify(currentFeatures);
}

进一步: 我收到错误:

 ERROR SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

这可能是由于使用以下方法构建的模型

constructor(rawData?: Partial<SubmitModel>) {
    Object.assign(this, rawData);
}

我的预期结果是将值数组包含在字符串值中。即:[“鸡蛋”,“火腿”]

成为:“ ['eggs','ham']”

0 个答案:

没有答案
相关问题