【问题标题】:Json object arrayJson 对象数组
【发布时间】:2020-02-18 02:43:30
【问题描述】:
.ajax({
  cache: false,
    url: '/Dashboard/ListofNames',
    data: {
        charSearch: txtboxvalue
    },
    success: function (res){
        var obj = JSON.parse(res); //this object contains 1 index which is 0. 
        var parseObj = JSON.parse(obj[0].JsonResult) // This line is working i successfully gets the data from index 0
        var parseObj2 = JSON.parse(obj[1].JsonResult) //This is not working because index 1 is not existing, what i want is instead of getting an undefined exception, i want to set the index 1 into an empty string or whatever solution that i wont get any undefined exception.

    }
});

任何建议都会对我有帮助,谢谢。

【问题讨论】:

  • 请澄清您的具体问题或添加其他详细信息以准确突出您的需要。正如目前所写的那样,很难准确地说出你在问什么。请参阅如何提问页面以帮助澄清此问题:stackoverflow.com/help/how-to-ask

标签: javascript json ajax object


【解决方案1】:
Considering your JSON.parse of object given the response as this object.
let res = [
    { name: "john", id: 1, JsonResult: "json-stringified-object-or-string" }
]
JSON.parse(res[0] ? res[0].JsonResult : '""');
JSON.parse(res[1] ? res[1].JsonResult : '""');

【讨论】:

  • 虽然此代码可能会为问题提供解决方案,但最好添加有关其工作原理/方式的上下文。这可以帮助未来的用户学习并将这些知识应用到他们自己的代码中。在解释代码时,您也可能会以赞成票的形式从用户那里获得积极的反馈。
【解决方案2】:

找到了解决办法。我检查了所有未定义的 obj 并为每个设置了一个新值。我创建了一个循环来检查每个未定义的 obj,之后我用空字符串创建了一个新对象并将其推送到我的 jsonresult 中。这不是一个好习惯,但它确实可以完成工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 2020-03-31
    • 2019-08-11
    • 2011-01-10
    • 1970-01-01
    • 2018-11-13
    相关资源
    最近更新 更多