向JSON对象数组添加新元素报错:对象不存在push函数
解决Cannot find function push in object [object Object]错误
嘿,踩坑了对吧?这个错误其实很好解决,咱们先搞清楚你的JSON结构到底长啥样:
你的原始JSON里,reservationNetworks对应的是一个对象,它的value属性里才包含真正的数组items——而你之前直接在obj['reservationNetworks']上调用push,相当于在对象上用数组方法,肯定会报错呀!
修正后的代码
var jsonStr = '{"key": "reservationNetworks", "value": {"type": "multiple", "elementTypeId": "COMPLEX", "items": [{"type": "complex","componentTypeId": "nw.service","componentId": null,"classId": "Reservation.Network","typeFilter": null,"values": {"entries": [{"key": "networkPath","value": {"type": "entityRef","classId": "Network","id": "6afec529-7fbc-45b7-8ac5-6abf944946ce","componentId": null,"label": "Label 1"}},{"key": "networkProfile","value": {"type": "entityRef","classId": "networkProfile","id": "187014d4-62f6-434c-a4da-c3e262d25ed4","componentId": null,"label": "Label 2"}}]}},{"type": "complex","componentTypeId": "nw.service","componentId": null,"classId": "Reservation.Network","typeFilter": null,"values": {"entries": [{"key": "networkPath","value": {"type": "entityRef","classId": "Network","id": "6afec529-7fbc-45b7-8ac5-6abf944946ce","componentId": null,"label": "Label 3"}},{"key": "networkProfile","value": {"type": "entityRef","classId": "networkProfile","id": "187014d4-62f6-434c-a4da-c3e262d25ed4","componentId": null,"label": "Label 4"}}]}}]}}'; var obj = JSON.parse(jsonStr); // 注意这里要定位到items数组,而不是reservationNetworks对象 obj['reservationNetworks'].value.items.push({ "type": "complex", "componentTypeId": "nw.service", "componentId": null, "classId": "Reservation.Network", "typeFilter": null, "values": { "entries": [ { "key": "networkPath", "value": { "type": "entityRef", "classId": "Network", "id": "6afec529-7fbc-45b7-8ac5-6abf944946ce", "componentId": null, "label": "Label 5" } }, { "key": "networkProfile", "value": { "type": "entityRef", "classId": "networkProfile", "id": "187014d4-62f6-434c-a4da-c3e262d25ed4", "componentId": null, "label": "Label 6" } } ] } }); jsonStr = JSON.stringify(obj);
关键修正点
- 原来的错误路径:
obj['reservationNetworks'].push(...)→ 这是对象,没有push方法 - 正确的数组路径:
obj['reservationNetworks'].value.items.push(...)→ 这才是你要添加元素的数组
这样修改后,就能顺利把包含Label 5和Label 6的新元素添加到数组里啦!
内容的提问来源于stack exchange,提问作者Legioon
相关产品推荐
相关产品推荐

