I have an array of objects and trying to extract the objects with a matched value of the array.
const A = [{_id: 'a', name: '1'}, {_id: 'b', name: '2'}, {_id: 'c', name: '3'}]
and const B = ['2', '3']
So, I want to match values of Array B to the Array A and get the objects into the Array C like const C = [{_id: 'b', name: '2'}, {_id: 'c', name: '3'}]
const C = A.forEach((list) => {
let key = []
if(list.includes[B]) {
key.push(list)
}
})
I am stuck at here, how can I push those objects to the Array C?
when you say matched value, it seems as if you're trying too match the name value.. if that's the case- this shoould work..
const A = [{_id: 'a', name: '1'},
{_id: 'b', name: '2'},
{_id: 'c', name: '3'}];
const B = ['2', '3'];
const C = [];
A.forEach((item) => {
if(B.filter(x=>x == item.name).length > 0) {
C.push(item)
}
});
I hope I have been helpful
const arrA = [{ _id: 'a', name: '1' }, { _id: 'b', name: '2' }, { _id: 'c', name: '3' }]; const arrB = ['2', '3']; var arrC = []; arrB.forEach(element => { arrA.forEach(element2 => { if (element === element2.name) { arrC.push(element2) } }); }); console.log(arrC);
You could filter the array.
const arrA = [{ _id: 'a', name: '1' }, { _id: 'b', name: '2' }, { _id: 'c', name: '3' }]; arrB = ['2', '3']; arrC = arrA.filter(({ name }) => arrB.includes(name)); console.log(arrC);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.