【问题标题】:Creating an object from looping through an array of objects with a nested array. Javascript通过使用嵌套数组循环遍历对象数组来创建对象。 Javascript
【发布时间】: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


【解决方案1】:

您应该将学生姓名推送到result.students,您可以使用空数组对其进行初始化。

使用另一个变量来保存所有匹配学生的总年龄。将年龄添加到此,然后计算最后的平均值。

// 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 = {
    hobby: target,
    students: [],
    averageAge: 0
  };
  var total_age = 0;
  for (var i = 0; i < arr.length; i++) {
    for (var k = 0; k < arr[i]['favorite hobbies'].length; k++) {
      if (arr[i]['favorite hobbies'][k] === target) {
        result.students.push(arr[i].name);
        total_age += arr[i].age;
      }
    }
  }
  if (result.students.length > 0) {
    result.averageAge = total_age / result.students.length;
  }
  return result;
}

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']
  },
];


console.log(findHobbies(students, 'swimming'));
/*
     should return: 
     {
       hobby: 'swimming',
        students: ['joe', 'dave', 'jane'],
       averageAge: 13
     }


    */

【讨论】:

    【解决方案2】:

    对于替代解决方案,您可以使用reduce 来实现结果

    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
    
    function findHobbies(arr, hobby) {
      const accumulator = {
        hobby,
        students: [],
        averageAge: 0,
      };
      const result = students.reduce((acc, curr) => {
        const { name, age, "favorite hobbies": sHobby } = curr;
        if (sHobby.includes(hobby)) {
          acc.students.push(name);
          acc.averageAge += age;
        }
        return acc;
      }, accumulator);
      result.averageAge /= result.students.length;
      return result;
    }
    
    console.log(findHobbies(students, "swimming"));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-16
      • 2021-05-20
      • 1970-01-01
      • 2015-10-15
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多