如何使用Javascript检索Json中的键/值对象?
我有个奇怪的问题 首先,我同时检索几个调用。并将返回的数据保存在名为“values”的变量中 我在controller中使用这段代码查看返回值:如何使用Javascript检索Json中的键/值对象?,javascript,angularjs,json,web,Javascript,Angularjs,Json,Web,我有个奇怪的问题 首先,我同时检索几个调用。并将返回的数据保存在名为“values”的变量中 我在controller中使用这段代码查看返回值: PrefsService .initialize() .then(function(values) { console.log("values",values); console.log("values[0]",values[0]); console.log("values[0].result",values[0].result); }) 我想使用“
PrefsService
.initialize()
.then(function(values) {
console.log("values",values);
console.log("values[0]",values[0]);
console.log("values[0].result",values[0].result);
})
我想使用“值[0].result”获取结果对象。但它总是给我一个“未定义”的值
为什么?
Thx此语法看起来很奇怪:
return {
values
}
它基本上是一个带有属性名的对象文字,但没有值。在任何情况下,您在首字母all
上标记的内容都是不必要的:
.then(function(values) {
return {
values
}
})
只需删除该部分。返回的值是承诺,使用它们作为承诺,就像您应该:
PrefsService
.initialize()
.then(function(values) {
values.map(function(valuePromise) {
valuePromise.then(function(value) {
console.log(value);
});
});
});
最直接的方法是返回实际值,而不是承诺:
function PrefsService($resource,PrefsResource,$q) {
var initialize = function() {
return $q
.all([
PrefsResource.get({key:"TwentyFourHourTime"}),
PrefsResource.get({key:"DecimalTime"}),
PrefsResource.get({key:"startDayOfWeek"}),
PrefsResource.get({key:"RoundingIncrement"}),
PrefsResource.get({key:"RoundingOption"})
])
.then(function(values) {
var returnValues = [];
values.forEach(function(v) {
v.then(function(a) {
returnValues.push(a);
})
});
return returnValues;
})
};
return {
initialize:initalize;
}
}
PrefsService
.initialize()
.then(function(values) {
console.log(values); //an array of the actual values, not the promises
})
值[0]。结果,请尝试此操作在什么时候尝试使用值[0]。结果。你所解释的应该有用。我猜这不仅仅是你的解释。初始化返回将是一个承诺。您正在调用initialize.then(…)?使用您所显示的值[0]。结果是获取它的正确方法。。可能是您在解决它之前访问它,因为您正在对象中包装
值。只需返回值
而不是{values}
,您将得到一个数组,该数组将具有map()
函数
您应该做的是返回值代码>类型错误:v.then不是位于Array.forEach(本机)的函数
function PrefsService($resource,PrefsResource,$q) {
var initialize = function() {
return $q
.all([
PrefsResource.get({key:"TwentyFourHourTime"}),
PrefsResource.get({key:"DecimalTime"}),
PrefsResource.get({key:"startDayOfWeek"}),
PrefsResource.get({key:"RoundingIncrement"}),
PrefsResource.get({key:"RoundingOption"})
])
.then(function(values) {
var returnValues = [];
values.forEach(function(v) {
v.then(function(a) {
returnValues.push(a);
})
});
return returnValues;
})
};
return {
initialize:initalize;
}
}
PrefsService
.initialize()
.then(function(values) {
console.log(values); //an array of the actual values, not the promises
})