Angular2使用.filter()从数组中获取索引和对象?

时间:2017-03-30 00:02:12

标签: angular indexing filter

有没有办法让下面的代码更简单?

let objectModified = this.objectsModified.filter(objectModified => {
  if(objectModified.index === this.objectCurrent.index) {
    return objectModified;
  }
})[0]; /*[0] because there is no way the could be .length > 1 */

if(objectModified) {
  let index = this.objectsModified.indexOf(objectModified);
  this.objectsModified[index] = "something";
}

else {
  this.objectsModified.push("something");
}

在我看来,必须有一个更智能,更易读的解决方案。但我无法理解。

1 个答案:

答案 0 :(得分:2)

使用findIndex会简化事情:

let objectModifiedIndex = this.objectsModified.findIndex(
  objectModified => objectModified.index === this.objectCurrent.index
);
if (objectModifiedIndex !== -1) {
  this.objectsModified[objectModifiedIndex] = "something";
} else {
  this.objectsModified.push("something");
}