首页 > 解决方案 > 查找数组索引失败

问题描述

我有一个组件数组(this.needle),其中一些但并非全部都有一个现有的 RMA,它是组件对象内的一个 RMA 对象。我正在尝试对 RMA 的删除进行编码。该方法接收记录,所以我知道 obj 有一个 rma 对象。

针数组是一个对象数组,如下所示:

[
    {
        cmp_auto_key: 3047,
        company_code: "FCAS2",
        condition_code: "AR",
        description: "PUMP, ELECT MOTOR DRIVEN",
        invc_number: "87259",
        msn: '11105",
        rma: {
            contact: "jsmith@co.com",
            disposition: 1,
            id: 714,
            status_id: 3,
            submit_deadline: "2019-11-08 00:00:00"
        }
    },
    {
        cmp_auto_key: 3047,
        company_code: "FCAS2",
        condition_code: "AR",
        description: "PUMP, ELECT MOTOR DRIVEN",
        invc_number: "87259",
        msn: '11111"
    }

]

这是删除代码:

if(confirm('Are you sure you want to delete this RMA?')) {
    let id = obj.rma.id;
    let idx = _.findIndex(this.needle, {id: obj.rma.id}); //produces error
    console.log('KILLER', this.needle[idx]);
    this.needle[idx].rma = null;
    console.log('KILLED', this.needle[idx]);
} // end if

此代码在指示的行上终止,因为并非数组中的所有元素都具有 RMA 对象,因此它返回

“无法设置未定义的属性 'rma'”

如果没有 rma 对象而不抛出异常,有没有办法让 findIndex 一起忽略记录?

非常感谢任何指导。

标签: lodash

解决方案


推荐阅读