在JavaScript中基于嵌套属性过滤掉数组

时间:2015-10-23 11:23:45

标签: javascript arrays filter

我有一个包含许多对象的数组

var personsArray = [
  {
    name: "Charles",
    numShifts: 0,
    availability: {
      Monday: true,
      Tuesday: true,
      Wednesday: true,
      Thursday: true,
      Friday: true,
      Saturday: true,
      Sunday: true
    }
  },
  (...)
];

我有一个工作日名称weekdayName

如何过滤掉数组,因此只有特定工作日具有可用性的对象才存在于数组中?

2 个答案:

答案 0 :(得分:4)

利用Array.filter

var personsAtWeekday = personsArray.filter(function (person) {
    return person.availability[weekdayName];
});

请注意,这不适用于IE8或更低版本。

另见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

答案 1 :(得分:0)

    var personsArray = [
    {
    name: "Charles",
    numShifts: 0,
    availability: {
        Monday: false,
        Tuesday: false,
        Wednesday: false,
        Thursday: true,
        Friday: true,
        Saturday: true,
        Sunday: true
        }
    },
    {
    name: "João",
        numShifts: 0,
    availability: {
        Monday: true,
        Tuesday: true,
        Wednesday: true,
        Thursday: false,
        Friday: false,
        Saturday: false,
        Sunday: false
        }
    },
    {
        name: "Maria",
        numShifts: 0,
        availability: {
            Monday: true,
            Tuesday: false,
            Wednesday: true,
            Thursday: true,
            Friday: false,
            Saturday: false,
            Sunday: false
        }
    }
];

var availableOnMonday = $.grep(personsArray, function (pArray, index) {
    return pArray.availability.Monday == true;
});

for (var i = 0; i < availableOnMonday.length; i++) {
    console.log(availableOnMonday[i].name);
}