鑒于我有這個物件陣列:
let array1 = [
{id: 1, name: "Test Item 1", price: 100, type: 'item'},
{id: 1, name: "Test Fee 1", price: 200, type: 'fee'},
{id: 3, name: "Test 3", price: 300, type: 'item'},
]
現在我想過濾,所以我只有以下陣列的每個鍵值都匹配的物件:
let array2 = [
{id: 1, type: "item"},
{id: 3, type: "item"},
]
這應該回傳array1[0]和array1[2]。我目前的解決方案是這樣,但如果 array2 有多個物件鍵要比較,它就不起作用:
array1.filter(row => {
return array2.find(r => {
return Object.entries(row).some(([key, value]) => r[key] === value);
})
});
uj5u.com熱心網友回復:
array1.filter((row) =>
array2.some((template) =>
Object.keys(template).every((key) => template[key] === row[key])
)
);
我認為上面評論中的答案比我的更干凈。
uj5u.com熱心網友回復:
在array1.filter()您可以迭代所有物件array2并使用比較鍵Object.keys()
let array1 = [
{id: 1, name: "Test Item 1", price: 100, type: 'item'},
{id: 1, name: "Test Fee 1", price: 200, type: 'fee'},
{id: 3, name: "Test 3", price: 300, type: 'item'},
]
let array2 = [
{id: 1, type: "item"},
{id: 3, type: "item"},
]
const res = array1.filter(row => {
for (const obj of array2) {
if (Object.keys(obj).every(k => obj[k] === row[k])) {
return row
}
}
})
console.log(res)
uj5u.com熱心網友回復:
Lodash如果你不介意:
const array1 = [{id: 1, name: "Test Item 1", price: 100, type: 'item'},{id: 1, name: "Test Fee 1", price: 200, type: 'fee'},{id: 3, name: "Test 3", price: 300, type: 'item'}];
const array2 = [{id: 1, type: "item"},{id: 3, type: "item"}];
const fn = _.overSome(array2.map(_.matches));
const result = _.filter(array1, fn);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520862.html
