How do I get the index of object in array using angular?
I need to have the index of an object in array so I can delete this part of the array. I tried using this
var index = this.urenRegistratie.indexOf(newDatum);
But it keeps returning -1 and I don’t know why this is happening.
this is the part of the code I have. it gets data out of a form in html and places that into my array, now I already have an if statement ready ( exisitingDatum ) , my code needs to be in there. Can someone please help me out a bit?
store(newValue:number, newDatum, newAanwezig, newComment){ const existingDatum = this.urenRegistratie.find(billable => { return billable.datum === newDatum; return }); if (!existingDatum) { let billable = new BillableHours(); billable.datum = newDatum; billable.hours = +newValue; billable.aanwezig = newAanwezig; billable.comment = newComment; if(billable.aanwezig == "Aanwezig" && billable.hours !== 0 && billable.datum !== null) { this.urenRegistratie.push(billable); } } if(existingDatum) { } }
Answers (1)
Add AnswerTo get the index of an object in an array using Angular, you can use the findIndex()
method available on JavaScript arrays. Here’s an example of how you can achieve this:
Assuming you have an array called myArray
containing objects and you want to find the index of an object based on a specific property value, you can do the following:
const objectToFind = { id: 2, name: 'John' }; // The object you want to find const index = myArray.findIndex(obj => obj.id === objectToFind.id); if (index !== -1) { console.log(`Object found at index ${index}`); } else { console.log('Object not found in the array'); }
In this example, findIndex()
is used to iterate over the array and check if the id
property of each object matches the id
of the objectToFind
. If a match is found, the index of that object is returned. If no match is found, -1
is returned.
Make sure to adjust the property used for comparison (id
in the example) based on the structure of your objects. You can modify the comparison logic inside the callback function of findIndex()
to match your specific requirements.
Note that the findIndex()
method returns the index of the first occurrence of the object that satisfies the condition. If you have multiple objects with the same property value, it will return the index of the first occurrence. If you need to find all occurrences, you can use a loop or other array methods to retrieve them.
By using the findIndex()
method, you can easily find the index of an object in an array based on a specific property value.