当数组本身是对象的属性时,无法访问该数组对象

Cannot access array objects when that array is itself an attribute of an object

本文关键字:对象 数组 访问 属性      更新时间:2023-09-26

我无法访问对象数组,该数组本身就是较大对象的属性。

console.log(skillprofiles);
console.log(skillprofiles.skills);

上面的语句返回一个由两个对象组成的数组,每个对象都有一个属性,该属性似乎是一个有效的对象数组(本例中为"skills")。

我无法访问"技能"数组属性。我最终想要获取的数据是"item_name"属性。据我所知,应该可以通过访问

skillprofiles[0].skills[0].item_name

有趣的是,用"typeof"验证"skills"属性的类型会返回"object"而不是数组。这可能是因为我在代码的早期将一个对象数组从一个对象转移到另一个对象。我认为我做得很好,似乎已经通过我的日志声明证实了这一点。

实际数据更新:

[{
"skillprofile_id": 144,
"skillprofile_name": " On-boarding",
"start_date": "January 30 2012",
"progress": 0,
"complete_date": " ",
"category": 1053,
"skills": [{
    "category": "Acquire: Onboard New Hires",
    "item_name": "3. On-boarding a New Hire - Day 1",
    "skill_type": "activity",
    "object_id": 68,
    "duration": "8:00:00",
    "sco_status_code": 6,
    "action": "activity",
    "has_forums": false
}, {
    "category": "Acquire: Onboard New Hires",
    "item_name": "4. On-boarding Checklist",
    "skill_type": "activity",
    "object_id": 67,
    "duration": "1:00:00",
    "sco_status_code": 6,
    "action": "activity",
    "has_forums": false
}]
}, {
"skillprofile_id": 143,
"skillprofile_name": " Setting Up Systems",
"start_date": "January 30 2012",
"progress": 0,
"complete_date": " ",
"category": 1053,
"skills": [{
    "category": "Acquire: Onboard New Hires",
    "item_name": "1. Office Organization",
    "skill_type": "activity",
    "object_id": 65,
    "duration": "4:00:00",
    "sco_status_code": 6,
    "action": "activity",
    "has_forums": false
}, {
    "category": "Acquire: Onboard New Hires",
    "item_name": "2. Welcome to the Team Documents",
    "skill_type": "activity",
    "object_id": 66,
    "duration": "2:00:00",
    "sco_status_code": 6,
    "action": "activity",
    "has_forums": false
}, {
    "category": "Acquire: Onboard New Hires",
    "item_name": "3. Welcome Documents: Feedback ",
    "skill_type": "activity",
    "object_id": 150,
    "duration": "1:00:00",
    "sco_status_code": 6,
    "action": "activity",
    "has_forums": false
}]
}]

更新2:

鉴于到目前为止的反应,我似乎应该能够运行以下程序:

$.each(skillprofiles, function(){
  console.log(this.skills)
});

我可以从控制台执行此操作,但当从我的代码

运行时,控制台语句会返回为"未定义"

在您的第一个代码块中,skills直接是skillprofiles的子级。而在第二个例子中,你写skillprofiles[o].skills。如果第一个例子有效,也许你的代码应该是:

skillprofiles.skills[0].item_name

使用该数据结构,正确的访问权限为:

skillprofiles[i].skills[j].item_name

你可以在这里看到它的工作原理:http://jsfiddle.net/jfriend00/wPLZZ/


skillprofiles是一个对象数组,因此您可以使用从数组中获得一个对象

skillprofiles[i]

该数组中的每个对象都有许多属性,其中一个属性名为skills,因此您可以使用获得该属性

skillprofiles[i].skills  

skills属性的内容是另一个数组,因此您可以使用以下内容从该数组中获取一个项目:

skillprofiles[i].skills[j]

该数组包含具有自己属性的对象,因此您可以使用以下命令访问特定属性:

skillprofiles[i].skills[j].item_name