我想基于输入“过滤”和对象:
const transactions =
[
{ _id:1,
amount:100,
tags:[{id: 1, label: A},
]
},
{ _id:2,
amount:200,
tags:[{id: 1, label: A},
{ id: 2, label: B}]
},
{ _id:3,
amount:500,
tags:[{ id: 2, label: B}
]
}
]
我想使用 map功能来获得最终结果为:
const tag = '1'
const transactionsFilter = transactions.map((transaction) => {
const filterT = transaction.tags.filter(
(tagFiltered) => tagFiltered._id === tag
);
console.log(filterT);
});
但我得到了“一个对象[null,null,null]
我想获得一个像这样的对象:
[
{ _id:1,
amount:100,
tags:[{id: 1, label: A},
]
},
{ _id:2,
amount:200,
tags:[{id: 1, label: A},
{ id: 2, label: B}]
},
]
因为只有前2个,所以标签的ID为:1
我该怎么做??
你可以filter()
在主数组上组合,然后some()
在标签数组上应用。
const transactions =
[
{ _id:1,
amount:100,
tags:[{id: 1, label: 'A'},
]
},
{ _id:2,
amount:200,
tags:[{id: 1, label: 'A'},
{ id: 2, label: 'B'}]
},
{ _id:3,
amount:500,
tags:[{ id: 2, label: 'B'}
]
}
]
let tag = 1
const res = transactions.filter(obj => obj.tags.some(tag => tag.id === 1));
console.log(res)