0

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 
}})
indra257
  • 66
  • 3
  • 24
  • 50
  • Possible duplicate of [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – Igor Feb 27 '19 at 15:28
  • 4
    You don't want to use `map`. `map` is a set operation, it doesn't iterate in a predictable manner. Use a `for each` loop and break on your desired condition. – Woohoojin Feb 27 '19 at 15:28

2 Answers2

4

You want to use find instead:

const newStaffName = this.staffData.find(staff => staff.id === staffId).name;
GCirs
  • 104
  • 5
  • I am not trying to find the name for that staffid. I am trying to update the name with the newStaffName – indra257 Feb 27 '19 at 15:58
  • Then change the trailing `).name;` for `).name = newStaffName;`. And don't assign it to a `const`. `find()` returns an element from the array that matches a condition, then you do with that element what you will. – GCirs Feb 27 '19 at 16:01
  • Sorry for not posting the question clearly. I am actually trying to update few parameters not just the name. That is the reason I have used map. Is there a way to update other parameters also with find? – indra257 Feb 27 '19 at 16:05
0

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);
msanford
  • 11,803
  • 11
  • 66
  • 93