I want to "filter" and object based on an input:
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}
]
}
]
I tried using map function to get the final result as:
const tag = '1'
const transactionsFilter = transactions.map((transaction) => {
const filterT = transaction.tags.filter(
(tagFiltered) => tagFiltered._id === tag
);
console.log(filterT);
});
But i got "an object [null, null, null]
I want to obtain an object like:
[
{ _id:1,
amount:100,
tags:[{id: 1, label: A},
]
},
{ _id:2,
amount:200,
tags:[{id: 1, label: A},
{ id: 2, label: B}]
},
]
Becouse just the first 2 , has the tag with id:1
How can I do it??
You can combine filter()
on the main array and then apply some()
on the tags array.
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)