角度:满足条件后,地图功能停止循环

时间:2019-02-27 15:26:30

标签: angular ecmascript-6 lodash

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

this.staffData.map(staff => {
  if(staff.id === staffId){
    staff.name === newStaffName;
    staff.dept = newDept;
    staff.address = newAddress//After this I want to break 
}})

2 个答案:

答案 0 :(得分:3)

您想改用find

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

答案 1 :(得分: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);