Given I have this array of objects:
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'},
]
Now i want to filter so I only have the objects where every key value of the following array match:
let array2 = [
{id: 1, type: "item"},
{id: 3, type: "item"},
]
This should return array1[0]
and array1[2]
.
My current solution has been this, but it wont work if array2 has multiple object keys to compare to:
array1.filter(row => {
return array2.find(r => {
return Object.entries(row).some(([key, value]) => r[key] === value);
})
});
CodePudding user response:
array1.filter((row) =>
array2.some((template) =>
Object.keys(template).every((key) => template[key] === row[key])
)
);
I think the answer in comment above is cleaner than mine.
CodePudding user response:
In array1.filter()
you can iterate all objects in array2
and compare keys using 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)
CodePudding user response:
Lodash if you don't mind:
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>