我有一个对象数组:
const guests = [
{ id: 1, rsvp: true },
{ id: 2, rsvp: false },
{ id: 3, rsvp: true },
{ id: 4, rsvp: false }
];
我想编写一个函数,只选择与rsvp'd的ID(guest)对应的对象。
function selectGuests(guests, id) {
list.forEach(function(id) {
if(id.true) {
push.SelectGuests();
}
});
return selectGuests;
}
然而,我得到了胡言乱语的结果。
对这一点或正确方向的任何帮助都将不胜感激!
干杯!
答案 0 :(得分:3)
<强>样本强>
const guests = [
{ id: 1, rsvp: true },
{ id: 2, rsvp: false },
{ id: 3, rsvp: true },
{ id: 4, rsvp: false }
];
var result = guests.filter(t=>t.rsvp);
console.log(result);
答案 1 :(得分:1)
使用forEach
function selectGuests(guests)
{
let result = [];
guests.forEach(function (guest) {
if (guest.rsvp) {
result.push(guest);
}
});
return result;
}
const guests = [
{ id: 1, rsvp: true },
{ id: 2, rsvp: false },
{ id: 3, rsvp: true },
{ id: 4, rsvp: false }
];
let a = selectGuests(guests);
console.log(a);
&#13;
或使用filter
方法
const guests = [
{ id: 1, rsvp: true },
{ id: 2, rsvp: false },
{ id: 3, rsvp: true },
{ id: 4, rsvp: false }
];
let a = guests.filter(function(item){return item.rsvp});
console.log(a);
&#13;
答案 2 :(得分:0)
这是一个不使用es6功能的简化版本。
function selectGuests(guests) {
var selectedGuests = []
// forEach gets the array elements (one by one) as first param
guests.forEach(function(guest) {
if(guest.rsvp) {
selectedGuests.push(guest)
}
})
return selectedGuests
}
// call it as follows
selectGuests(guests)