【发布时间】:2021-05-25 22:51:31
【问题描述】:
我在遍历数组内的数组和数组内的对象并将这些名称推入我的结果数组时遇到问题。我知道如何在我的结果对象中创建新属性,但为了做到这一点,我需要将名称推送到我创建的名称数组中。也许我没有正确循环它。
var students = [{
name: 'joe',
color: 'blue',
age: 13,
height: 61,
"favorite hobbies": ['drawing', 'sports', 'swimming'],
birthday: '1/12/1992'
},
{
name: 'dave',
color: 'red',
age: 14,
height: 60,
"favorite hobbies": ['swimming', 'biking', 'hiking'],
birthday: 'January 29, 1992'
},
{
name: 'sally',
color: 'yellow',
age: 13,
height: 64,
"favorite hobbies": ['biking', 'singing', 'dancing']
},
{
name: 'jane',
color: 'white',
age: 12,
height: 58,
"favorite hobbies": ['dancing', 'swimming', 'drawing']
},
{
name: 'kayla',
color: 'blue',
age: 14,
height: 62,
"favorite hobbies": ['hiking', 'sports', 'drawing']
},
];
// findHobbies, given an array of student objects, returns:
// an object containing three properties:
// hobby
// the targeted hobby
// students
// array of student names that match target hobby
// averageAge
// average age of students that match target hobby
var findHobbies = function(arr, target) {
var result = {};
result.hobby = target;
// result.averageAge =
for (var i = 0; i < arr.length; i++) {
var names = [];
for (var k = 0; k < arr[i]['favorite hobbies'].length; k++) {
// console.log(arr[i]['favorite hobbies'][k])
if (arr[i]['favorite hobbies'][k] === target) {
array.push(arr[i].name);
}
console.log(array)
}
}
}
console.log(findHobbies(students, 'swimming'));
/*
should return:
{
hobby: 'swimming',
students: ['joe', 'dave', 'jane'],
averageAge: 13
}
*/
【问题讨论】:
-
什么是
array? -
我的意思是输入名称数组。
标签: javascript arrays object nested push