我是Javascript的新手。我有一个对象,我需要将它与变量进行比较,然后如果满足条件,我会做一些事情。如何才能访问我需要的字段?
我接受了这个变量:$scope.acceptedProjects['hash'][key]['title']
这是我的代码:
$scope.overlappingDates = overlappingDates;
$scope.acceptedProjects = invitationService.acceptedProjects;
for(var value in $scope.overlappingDates) {
for(var key in $scope.acceptedProjects['hash']) {
console.log($scope.overlappingDates);
console.log($scope.acceptedProjects['hash'][key]['title']);
}
}
return;
如果我尝试$scope.overlappingDates[value]
,它会返回
我只需要切片或做一些事情来将这个庞大的名称转换为var。
答案 0 :(得分:0)
从我看到的浏览器输出中,overlap1是包含内部对象的数组。这就是如何获取对象值
for (var i = 0; i < overlap1.length; i++;){ //iterate over all objects inside array
var el = overlap1[i];
//get variables of object
var projectDateId = el.project_date_id// or el["project_date_id"];
var projectsProjectId = el.projects_project_id// or el["projects_project_id"];
//do something with this variables
}
答案 1 :(得分:0)
不确定我是否有你想要达到的目标。但是一步一步地看一下这个抽象的例子,并了解这里发生了什么。我希望这可以帮助您更熟悉访问对象属性和数组项:
var data = {
prop1: [
{meaning_property: 1},
{meaning_property: 2},
{meaning_property: 3}
],
prop2: [
{meaning_property: 4},
{meaning_property: 5},
{meaning_property: 6}
]
};
var found_field_name = null;
var found_item_index = -1;
var looking_for_value = 5;
// loop through data's fields
for (var prop in data) {
// access the value of object's field prop1, prop2 etc...
var arr = data[prop];
// loop through array
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
// item property value meets the condition?
if (item.meaning_property === looking_for_value) {
// remember field name for array
found_field_name = prop;
// remember item index in array
found_item_index = i;
// break the cycle here, we've found what we need
break;
}
/**
* item.meaning_property you can also access in different ways
* arr[i].meaning_property
* data[prop][i].meaning_property
* data["prop1"][0].meaning_property
* data.prop1[0].meaning_property
*/
}
}
// if we found something during previos loop
if (found_field_name !== null) {
// access the corresponding array
var arr = data[found_field_name];
// access the corresponding item
var item = arr[found_item_index];
console.log("Item found", found_field_name, found_item_index, arr, item);
}
else {
console.log("No items met the criteria");
}
尝试使用此代码,我相信,您最终会找到解决问题的方法。