Javascript按嵌套对象属性过滤

时间:2019-05-29 23:24:54

标签: javascript jquery

我有以下数组:

arr = [{id: 1, type: {name: "Approval", id: 1}},
       {id: 2, type: {name: "Rejection", id: 2}},
       {id: 3, type: {name: "Approval", id: 1}}
      ];

为什么以下产生和[]结果?我希望得到2个对象的数组(即ID 1和3)。

$.grep(arr, function(a) { return a.type.name === "Approval"; })

有想法吗?

2 个答案:

答案 0 :(得分:1)

为什么在这里使用jQuery? Javascript为此提供了完美的方法。 filterfind

const arr = [
{id: 1, type: {name: "Approval", id: 1}},
{id: 2, type: {name: "Rejection", id: 2}},
{id: 3, type: {name: "Approval", id: 1}}
];
      
const matches = arr
    .filter(entry => entry.type.name === 'Approval')
console.log(matches)

答案 1 :(得分:0)

return是js中的保留关键字。因此,您不能将其用作变量并无法访问其属性。

相反,您需要访问a变量的属性:

$.grep(arr, function(a) { return a.type.name === "Approval"; })
相关问题