访问对象数组的元素

时间:2018-01-28 05:16:33

标签: javascript arrays object

我有一个对象数组:

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;
}
然而,我得到了胡言乱语的结果。

对这一点或正确方向的任何帮助都将不胜感激!

干杯!

3 个答案:

答案 0 :(得分:3)

使用array.filter()

<强>样本

 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

&#13;
&#13;
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;
&#13;
&#13;

或使用filter方法

更简单

&#13;
&#13;
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;
&#13;
&#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)