简体   繁体   中英

Filter array of objects by property

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?

Use filter and some:

const myArrayFiltered = obj.filter( el => {
  return value.some( f => {
    return f.surname === el.name;
  });
});

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

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".

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));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM