好的,我们都知道这有效:
vm.myObject = {
required : "This field requires data",
.....
}
但是当属性'keys'和'values'来自json文件时,如何动态创建同一个对象,例如:
json:
[
{ "key" :"required", "value": "This field requires data"},
.....
]
服务:
var myObject = {}
DynamicObjSvc.get()
.success(function(data){
data.forEach(function(item){
// pass each key as an object property
// and pass its respective value
?????????
})
.....
更新
Kavemen大部分都是正确的,结果证明这是解决方案:
var myObject = {};
DynamicObjSvc.all()
.success(function(data){
angular.forEach(data, function(msg) {
myObject[msg.key] = msg.value; <-- his answer was incorrect here
});
$fgConfigProviderRef.validation.message(myObject);
})
.error(function(err){
console.log(err.message);
})
答案 0 :(得分:2)
您可以使用angular.forEach
和括号表示法在Javascript中设置(和获取)对象属性
var myObject = {}
DynamicObjSvc.get().success(
function(data) {
angular.forEach(data, function(value, key) {
myObject[key] = value;
});
}
);
另见MDN的Working with Objects
修改
我现在看到你的data
实际上是一个对象数组,而不仅仅是一个对象,所以是的,上面的代码可能会让你误入歧途。
在任何情况下,使用括号表示法动态设置对象属性的方法都是合理的;可以重新设计循环以处理您的data
数组:
//we have an array of objects now
var myObjects = [];
DynamicObjSvc.get().success(
function(data) {
//for each object in the data array
for(var i = 0; i < data.length; i++) {
//create and populate a new object for the ith data element
var newObject = {};
angular.forEach(data[i], function(value, key) {
newObject[key] = value;
});
//and add it to the overall collection
myObjects.push(newObject);
}
}
);