C#结合AJAX获取嵌套JSON对象值:如何正确读取categoryId字段
问题解决方法
你无法通过result.productCategoryMappings.categoryId读取值的核心原因是:JSON结构中productCategoryMappings是数组类型,不是普通对象,不能直接通过.运算符访问内部嵌套对象的属性,需要先通过数组索引定位到对应的元素,再读取元素的属性。
基础读取方式(数组只有1个元素的场景)
如果确认接口返回的productCategoryMappings数组永远至少包含1个元素,可以直接通过下标0读取第一个元素的categoryId:
const categoryId = result.productCategoryMappings[0].categoryId
容错写法(避免数组为空时报错)
如果存在数组为空的可能,建议先做合法性判断再读取,避免前端抛出undefined读取异常:
success: function(result) { // 原有读取name的逻辑 console.log(result.name) let categoryId = null // 先判断数组存在且长度大于0,可选链语法兼容主流现代浏览器 if (result.productCategoryMappings?.length > 0) { categoryId = result.productCategoryMappings[0].categoryId } // 后续业务逻辑 console.log(categoryId) }
多元素场景读取所有categoryId
如果productCategoryMappings数组可能包含多个元素,需要批量读取所有categoryId,可以用数组遍历方法实现:
const categoryIdList = result.productCategoryMappings.map(item => item.categoryId) // 输出结果为 [21],多元素时会把所有categoryId存入数组
内容的提问来源于stack exchange,提问作者mohtashim
相关产品推荐
相关产品推荐

