[英]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.