indra257
indra257

Reputation: 86

Angular: Map function stop looping after a condition is met

I have my angular code as below. I am looping in to my array to find certain element and map the data. After I find my element, I want to stop looping as the element is unique and I don't want further checking

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

Upvotes: 0

Views: 1394

Answers (2)

msanford
msanford

Reputation: 12237

Here is a straightforward, annotated alternative with 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);

Upvotes: 0

GCirs
GCirs

Reputation: 104

You want to use find instead:

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

Upvotes: 4

Related Questions