[英]Extracting unique values from an array of objects where value is a nested object in JavaScript
[英]Extracting values from Array of nested Objects in JavaScript
我有一個對象數組,並嘗試使用數組的匹配值提取對象。
const A = [{_id: 'a', name: '1'}, {_id: 'b', name: '2'}, {_id: 'c', name: '3'}]
和const B = ['2', '3']
所以,我想將數組 B 的值與數組 A 匹配,並將對象放入數組 C 中,例如const C = [{_id: 'b', name: '2'}, {_id: 'c', name: '3'}]
const C = A.forEach((list) => {
let key = []
if(list.includes[B]) {
key.push(list)
}
})
我被困在這里,如何將這些對象推送到數組 C?
當你說匹配值時,似乎你試圖太匹配名稱值..如果是這樣的話 - 這應該有效..
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)
}
});
我希望我有所幫助
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);
你可以過濾數組。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.