JSON数据显示在控制台中,但在浏览器中显示为“未定义”

时间:2019-04-08 16:10:00

标签: javascript jquery json methods append

我有一些元素共享值的JSON数据,因此我将数据简化为正确嵌套值的新JSON:

 (4) [{…}, {…}, {…}, {…}]
   0:
    SameGroup: Array(3)
     0: {Role: "SomeRole", IsFilled: false, isActive: true}
     1: {Role: "AnotherRole", IsFilled: true, isActive: false}
     2: {Role: "OtherRole", IsFilled: false, isActive: true}
     length: 3
     Title: "Title-A"
   1: {Title: "Title-B", SameGroup: Array(2)}

我正在尝试通过替换已过滤的数据源,将新的JSON附加到唯一的div(我之前已经工作过)中。在控制台中,我可以看到JSON树,但是在浏览器中,它以undefined.

的形式出现

我认为在我的旧代码中实现新的JSON存在一个问题(如何过滤该问题)。对这个有什么想法吗?

JS代码段:

function _displayForm() {
    let titleKeyHolder = [];
    let titleArr = [];

    jsonData.d.results.forEach(function(item) {
        titleKeyHolder[item.Title] = titleKeyHolder[item.Title] || {};
        let obj = titleKeyHolder[item.Title];
        if(Object.keys(obj).length == 0)
            titleArr.push(obj);

        obj.Title = item.Title;
        obj.SameGroup = obj.SameGroup || [];

        obj.SameGroup.push({ Role:item.Role, IsFilled: item.IsFilled, isActive: item.IsActive });
    });

    console.log(titleArr);

    let jobTitle = titleArr // ------ based on the JSON shape, I'm guessing I can't have titleArr written like this
        .filter(x => x.Title !== "");

        jobTitle.forEach(val => {
            let $clonedDiv = $("#template").clone();
            $clonedDiv.removeAttr("id");

            $clonedDiv
               .find("#display-form-job-title")
               .append(val.Title);

        // other code
}

_displayForm();

旧JSON:https://jsfiddle.net/vrep307f/

1 个答案:

答案 0 :(得分:0)

我注意到您在转换接收到的数据时遇到问题,请尝试从此代码中汲取灵感

<script>

var text = '{"d":{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}}';




var obj = JSON.parse(text);


obj.d.employees.forEach(function(item) {

console.log(item.firstName);
})


</script>