Reputation: 93
I have an array of objects:
const obj = [
{ name: 'Test', age: 25 },
{ name: 'App', age: 27 },
{ name: 'Const', age: 28 },
];
and I have the other one:
const value = [
{ surname: 'Test', age: 54 },
{ surname: 'Back', age: 54 },
{ surname: 'Front', age: 54 },
{ surname: 'Const', age: 54 },
{ surname: 'App', age: 54 },
];
Now, I want to leave in the second array only objects, which have name === surname and the other ones delete. Keys must be different, but the values in them must be the same. For example: {name: "Test", age: 25} === {surname: "Test", age: 54}(it's just an example) How to make it?
Upvotes: 0
Views: 148
Reputation: 88
Try this
const obj = [
{ name: 'Test', age: 25 },
{ name: 'App', age: 27 },
{ name: 'Const', age: 28 },
];
let value = [
{ surname: 'Test', age: 54 },
{ surname: 'Back', age: 54 },
{ surname: 'Front', age: 54 },
{ surname: 'Const', age: 54 },
{ surname: 'App', age: 54 },
];
const names = obj.map(el => el.name);
value = value.filter(el => names.includes(el.surname));
or like this:
const obj = [
{ name: 'Test', age: 25 },
{ name: 'App', age: 27 },
{ name: 'Const', age: 28 },
];
const names = obj.map(el => el.name);
const value = [
{ surname: 'Test', age: 54 },
{ surname: 'Back', age: 54 },
{ surname: 'Front', age: 54 },
{ surname: 'Const', age: 54 },
{ surname: 'App', age: 54 },
].filter(el => names.includes(el.surname));
Upvotes: 1
Reputation: 835
Use embedded Javascript's find and filter methods:
value.filter(k =>
obj.find(v => v.name === k.surname)
)
This basically says "filter all values from value
array that match this criteria". And the criteria is "find values in obj
where name equals surname".
Upvotes: 1
Reputation: 2784
Your have to use filter
and see if there is a key in the second list.
And don't forget to reassign the result of filter()
to the value
list as the filter doesn't change the original list, but returns a new, filtered one.
value = value.filter(oneVal => obj.find(o => o.name === oneVal.surname))
More on filter() here
Upvotes: 1
Reputation: 176
Use filter and some:
const myArrayFiltered = obj.filter( el => {
return value.some( f => {
return f.surname === el.name;
});
});
Upvotes: 1