简体   繁体   中英

Filter out array based on nested properties in JavaScript

I have an array with many objects

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

I have a weekday name weekdayName .

How can I filter out the array, so only those objects with availability on the specific weekday exists in the array?

Leverage Array.filter :

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

Note that this will not work on IE8 or below.

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

    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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM