Angular:映射函数在满足条件后停止循环

问题描述 投票:0回答:2

我的角度代码如下。我循环到我的数组,以找到某些元素并映射数据。找到我的元素后,我想停止循环,因为元素是唯一的,我不想进一步检查

this.staffData.map(staff => {
  if(staff.id === staffId){
    staff.name === newStaffName;
    staff.dept = newDept;
    staff.address = newAddress//After this I want to break 
}})
angular ecmascript-6 lodash
2个回答
3
投票

你想用find代替:

const newStaffName = this.staffData.find(staff => staff.id === staffId).name;

0
投票

这是一个用Array.findIndex()直接注释的替代方案:

staff = [{
    name: "Mark",
    dept: "Sales",
    address: "123 Fake St"
  },
  {
    name: "Jim",
    dept: "Sales",
    address: "123 Real St"
  },
  {
    name: "Fred",
    dept: "Sales",
    address: "123 Imaginary Ln"
  }
];

console.dir(staff);

// Find the index of the person based on whatever criteria you want
index = staff.findIndex(person => person.name === "Jim");

// Update that index with a new object
staff[index] = {
  // Retain values you don't want to change
  name: staff[index].name,
  address: staff[index].address,
  
  // Change those you do
  dept: "Development"
}

console.dir(staff);
© www.soinside.com 2019 - 2024. All rights reserved.