javascript - JSON:未捕获类型错误:无法设置未定义的属性 'values'

标签 javascript jquery json

我试图将页面上所有文本区域的值传递到 JSON 表。 由于某种原因,我收到“无法设置未定义错误的值”,我不明白,因为我的 Json 是之前定义的。

这是包含 2 个函数的代码。

function parseToJson() {
    var json = {};

    $("input.invoice_details").each(function () {
        json[this.id] = $(this).val();
    });

    $("select.invoice_details").each(function () {
        json[this.id] = $(this).val();
    });

    json.categories = {};

    $("textarea.invoice_categories").each(function () {
        if (this.value.trim() !== '') {
            json.categories[this.id].values = splitInput(this);
            json.categories[this.id].label = this.name;
        }
    });
    console.log(JSON.stringify(json));
    generatePreveiw(json);
}

function splitInput(textArea) {
    var input = textArea.value.trim();
    var lines = input.split("\n");
    var array = [];
    $.each(lines, function (indexLine, line) {
        var columns = line.split("\t");
        var obj = {};
        $.each(columns, function (indexColumn, column) {
            var columnName = columnsName.columnsName[indexColumn].name;
            obj[columnName] = column;
        });
        array.push(obj);
    });
    return array;
}

最佳答案

        json.categories[this.id].values = splitInput(this);
        json.categories[this.id].label = this.name;

应该是:

        json.categories[this.id] = {
            values: splitInput(this),
            label: this.name
        };

如果您没有先创建对象,则无法设置该对象的属性。您可以使用此对象字面量语法一步创建对象及其属性。

关于javascript - JSON:未捕获类型错误:无法设置未定义的属性 'values',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33255666/

相关文章:

javascript - LAMP:浏览器不支持 ubuntu 中的 javascript

javascript - 无法从 Select2 中选择任何项目

python - 从字典列表中查找具有用户输入 key 的字典

javascript - 将 Json 保存在 Javascript 变量中

c++ - XSLT 到 C++ 以从 XML 获取 JSON

javascript - 如何使用按钮点击来显示和显示div?

javascript - 正则表达式:必须存在的组,但事先未知它将在哪里

javascript - 有没有办法限制 Owl Carousel 中的图像或页面数量

jquery - 溢出-y : scroll is set to some element in body 时窗口滚动事件未触发

JavaScript:带有对象参数的对象构造