我正在尝试从请求返回的 json 对象中获取特定值。但是我使用的 sintax 不起作用。返回的值为undefined
。如何获取name
json对象中键的值?
响应存储在客户变量中。
$http.get('url').
then(function successCallback(response){
var costumers = response;
console.log(costumers['data']['costumers']['name']);
}, function errorCallback(response){
});
JSON 对象
{data: "{"costumers":[{"id":"1","name":"John"},{"id":"2","name":"Mary"}]}"}
customers
是一个数组,要访问数组元素,您需要将索引写入其后面的方括号中。在这种情况下,如果要访问数组的第一个元素(索引 0),可以这样做:
$http.get('url').
then(function successCallback(response){
var costumers = response;
console.log(costumers['data']['costumers'][0]['name']);
}, function errorCallback(response){
});
或者使用 for 循环记录所有客户:
$http.get('url').
then(function successCallback(response){
var costumers = response;
for(let customer of costumers['data']['costumers']) {
console.log(customer['name']);
}
}, function errorCallback(response){
});
所有这些只有在对象语法正确的情况下才有效,它应该是这样的:
{data: {costumers:[{id:"1",name:"John"},{id:"2",name:"Mary"}]}}
而不是您发布的对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句