如果找到,如何在数组中添加元素?

How to add element in array if it was found?

我用这个方法在数组中查找对象:

lat arr = [];
found = this.obj[objKey].filter(item => item[internKeyName] == 7047);
arr.push(found);

问题是,如果找不到元素,它会将此作为 undefined 添加到数组 arr。如何避免这种情况?

为什么它找不到带有键的元素:"subjectId":

let objKey = 7047;
let k = "subjectId";
let v = 7047;

found = this.obj[objKey].filter(item => item[k] == v);

console.log(found);// undefined

您可以通过在将其推送到数组之前检查长度 found 来避免这种情况。

lat arr = [];
found = this.obj[objKey].filter(item => item[internKeyName] == 7047);
found.length > 0 && arr.push(...found);

我正在使用 spread syntax 将每个元素作为其自己的项目推送到新数组,我认为这就是您想要的。如果您希望所有找到的项目都成为其自己的数组项目,则可以删除 ...

函数 filter 不会 return undefined,return 将是一个空数组 (如果 none 元素满足条件).

Problem is that if element was not found it added this as undefined to array arr.

你可能想找到一个特定的元素,所以,如果你只想要一个对象而不是只有一个索引的数组,我建议你使用函数 find

lat arr = [];
found = this.obj[objKey].find(item => item[internKeyName] == 7047);
if (found) arr.push(found);

您可以直接推送包含所需对象的展开数组,空数组不会展开(spread syntax ...)。

arr.push(...this.obj[objKey].filter(item => item[internKeyName] == 7047));