在数组中查找对象?

时间:2019-09-28 14:19:30

标签: javascript arrays reactjs object

想象一下,我有一个这样的对象数组(虚拟代码):

const chosenBets = [{...}, {...}] // 2 items

我想从数组中删除特定项目:

{id: 0, // is unique
 label: 1,
 odd: 1.33,
 oddIndex: 0,
 team_home: "Liverpool",
 team_away: "Sheffield United",
 matchCardIndex: 0,}

现在该数组为:

const chosenBets = [{...}] // 1 items

我将如何实现?

3 个答案:

答案 0 :(得分:5)

您可以使用数组filter

const chosenBets = [{
  id: 0, // is unique
  label: 1,
  odd: 1.33,
  oddIndex: 0,
  team_home: "Liverpool",
  team_away: "Sheffield United",
  matchCardIndex: 0
}, {
  id: 1, // is unique
  label: 1,
  odd: 1.33,
  oddIndex: 0,
  team_home: "Liverpool",
  team_away: "Sheffield United",
  matchCardIndex: 0
}];

const filteredData = chosenBets.filter(item => item.id === 1);
console.log(filteredData);

答案 1 :(得分:1)

您可以使用splice

var a = [{
    id: 0, // is unique
    label: 1,
    odd: 1.33,
    oddIndex: 0,
    team_home: "Liverpool",
    team_away: "Sheffield United",
    matchCardIndex: 0,
  },
  {
    id: 0, // is unique
    label: 11,
    odd: 1.33,
    oddIndex: 0,
    team_home: "Liverpool",
    team_away: "Sheffield United",
    matchCardIndex: 0,
  }
]
a.forEach((e, j) => {
  if (e.label == 1)
    a.splice(j, 1);
})
console.log(a)

答案 2 :(得分:0)

如果您要删除特定且唯一的对象,我将执行以下操作:

let chosenBets = [{
  id: 0, // is unique
  label: 1,
  odd: 1.33,
  oddIndex: 0,
  team_home: "Liverpool",
  team_away: "Sheffield United",
  matchCardIndex: 0
}, {
  id: 1, // is unique
  label: 1,
  odd: 1.33,
  oddIndex: 0,
  team_home: "Liverpool",
  team_away: "Sheffield United",
  matchCardIndex: 0
}];

let index = chosenBets.findIndex(({id}) => id === 1);

// if you want to mutate the original array, otherwise use `slice`
chosenBets.splice(index, 1);
console.log(chosenBets);
如果要删除一组元素,而不仅仅是一个元素,

filter会更好。原因是,它一直在迭代数组中的所有元素,因此即使您要删除的元素是第一个元素,它也总是迭代整个数组。 使用findIndex可以迭代直到找到元素,然后返回索引:平均起来,它的循环次数更少。