[英]How do I get the index of object in array using angular?
我需要在數組中有一個 object 的索引,這樣我就可以刪除數組的這一部分。 我試過用這個:
var index = this.urenRegistratie.indexOf(newDatum);
但它一直返回 -1,我不知道為什么會這樣。
這是我擁有的代碼的一部分。 它從 html 中的表單中獲取數據並將其放入我的數組中,現在我已經准備好一個 if 語句(exisitingDatum),我的代碼需要在那里。 有人可以幫我一下嗎?
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) {
}
}
findIndex() 方法返回數組中滿足提供的測試 function的第一個元素的索引。 否則,它返回 -1,表示沒有元素通過測試。
如果您有這樣的對象數組,請嘗試使用findIndex
:
const a = [ { firstName: "Adam", LastName: "Howard" }, { firstName: "Ben", LastName: "Skeet" }, { firstName: "Joseph", LastName: "Skeet" } ]; let index = a.findIndex(x => x.LastName === "Skeet"); console.log(index);
添加到@StepUp的答案(請 select 他的回答最好,因為它很好地回答了這個問題):
查找索引與 Angular 無關,而是 Vanilla JavaScript。
在您的情況下,您需要一個 function 作為參數,使用findIndex在數組“haystack”中搜索newDatum
“needle”:
var getNewDatumIndex = (array, newDatumNeedle) => {
return array.findIndex(x => x.newDatum === newDatumNeedle);
}
如果需要,您還可以在數組原型中添加方法,以省略第一個參數:
Array.prototype.getNewDatumIndex = (newDatumNeedle) => {
return this.findIndex(x => x.newDatum === newDatumNeedle);
}
一個簡單而優雅的解決方案是使用_.isEqual ,它使用lodash庫進行深度比較
Npm Package -- https://www.npmjs.com/package/lodash
const a = [
{ firstName: "Adam", LastName: "Howard" },
{ firstName: "Ben", LastName: "Skeet" },
{ firstName: "Joseph", LastName: "Skeet" }
];
const find = { firstName: "Joseph", LastName: "Skeet" }
index = a.findIndex(x => _.isEqual(x, find));
console.log(index);
store(newValue: number, newDatum, newAanwezig, newComment) { let index = this.urenRegistratie.indexOf(existingDatum);
const existingDatum = this.urenRegistratie.find(billable => {
return billable.datum === newDatum;
return
});
if (index != -1) {
let index = this.urenRegistratie.indexOf(existingDatum);
existingDatum.splice(index, 1)
} else {
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);
}
}
}
有時候,如果你通過id比較,你需要parseint,因為對象的id是一個字符串。 關心這個
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.